TS | 进阶 高级类型
Partial, Readonly, Record, Pick
先看看它们的源码定义:
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T, pick a set of properties whose keys are in the union K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
Record
以 typeof 格式快速创建一个类型,此类型包含一组指定的属性且都是必填。
type Coord = Record<'x' | 'y', number>;
// 等同于
type Coord = {
x: number;
y: number;
}
Partial
type Coord = Partial<Record<'x' | 'y', number>>;
// 等同于
type Coord = {
x?: number;
y?: number;
}
Readonly
type Coord = Readonly<Record<'x' | 'y', number>>;
// 等同于
type Coord = {
readonly x: number;
readonly y: number;
}
Pick
type Coord = Record<'x' | 'y', number>;
type CoordX = Pick<Coord, 'x'>;
// 等用于
type CoordX = {
x: number;
}
链判断运算符
1 /* */
2 a?.b;
3 // a b undefined a.b
4 a == null ? undefined : a.b;
5
6 a?.[b];
7 // a b undefined a[b] 8 a == null ? undefined : a[b];
9
10 a?.b()
11 // a b undefined a.b() a.b 12 a == null ? undefined : a.b();
13
14 a?.()
15 // a undefined a()
16 a == null ? undefined : a();
阅读剩余
版权声明:
作者:chun
链接:https://chun53.top/1449.html
文章版权归作者所有,未经允许请勿转载。
THE END