// 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];
};
// Pick a set of properties from T
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
// A type with a given set of properties of a given type
type Record<K extends string | number, T> = {
[_ in K]: T;
}
// A proxy for a given type
type Proxy<T> = {
get(): T;
set(value: T): void;
}
// Proxify all properties in T
type Proxify<T> = {
[P in keyof T]: Proxy<T[P]>;
}
···
用例比如React组件state类型,以前对State里面每个属性都必须使用nullable type:
type State = { prop1?: TYPE1, prop2?: TYPE2 }
否则调用setState并只修改prop1或prop2时会出错。
现在只要把setState的声明改写成上面Partial的形式就可以了。