interface Person {
name: string;
age: number;
}
const sem: Person = { name: 'semlinker', age: 30 };
type Sem= typeof sem; // -> Person
function toArray(x: number): Array<number> {
return [x];
}
type Func = typeof toArray; // -> (x: number) => number[]
keyof
用于获取某种类型的所有键,其返回类型是联合类型。
interface Person {
name: string;
age: number;
location: string;
}
type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[]; // number | "length" | "push" | "concat" | ...
type K3 = keyof { [x: string]: Person }; // string | number
in
用来遍历枚举类型
type Keys = "a" | "b" | "c"
type Obj = {
[p in Keys]: any
} // -> { a: any, b: any, c: any }
infer
在条件类型表达式 T extends U ? X : Y 中,我们可以用 infer 声明(推断)一个类型变量并且对它进行使用。
demo
// infer P 表示待推断的函数参数。
// 如果 T 能赋值给 (param: infer P) => any,则结果是 (param: infer P) => any 类型中的参数 P,否则返回为 T。
type ParamType<T> = T extends (param: infer P) => any ? P : T;
interface User {
name: string;
age: number;
}
type Func = (user: User) => void;
type Param = ParamType<Func>; // Param = User
type AA = ParamType<string>; // string
ReturnType 中的 infer
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
根据 extends 可知道这里的作用:如果传入的类型 T 能够赋值给 (...args: any) => R 则返回类型 R。
但是这里的 R 外部并没有指定
typescript 操作符
操作符
extends 条件类型
上面的类型表示何时T可分配给U类型为X,否则类型为Y。
typeof
用来获取一个变量声明或者对象的类型
keyof
用于获取某种类型的所有键,其返回类型是联合类型。
in
用来遍历枚举类型
infer
在条件类型表达式
T extends U ? X : Y
中,我们可以用 infer 声明(推断)一个类型变量并且对它进行使用。demo
ReturnType 中的 infer
根据
extends
可知道这里的作用:如果传入的类型 T 能够赋值给 (...args: any) => R 则返回类型 R。但是这里的
R
外部并没有指定