function fn():string{
return '123'
}
type fnType = typeof fn; // type fnType = () => string
let a: ReturnType<fnType>;
a = '123' // string
为了避免混乱,ts限制typeof关键字后面只能跟标识符(变量名、函数名等)或对象属性。
// 错误
function fn():string{
return '123'
}
let a:typeof fn() = '123'
// 正确
let o = {
a: '123'
}
let a: typeof o.a = '123'
索引访问类型(Indexed Access Types)
ts可以通过索引访问类型。可以通过type、interface或对象来设置类型。
// 对象
let o = {
a: '123'
}
let a: typeof o['a'] = '123'
// 接口
interface O1 {
a: string
}
type Oa = O1['a']
// 类型别名
type O2 = {
a: string
}
type Ob = O2['a']
甚至你还可以使用联合类型。
type A = {
a: string,
b:number
}
type B = A['a' | 'b'] // string | number
type C = A[keyof A] // string | number
Mapped Types
有些时候你可能要重复定义某些类型,如果你不想编写重复的代码,可以使用映射类型。
type A<Type> = {
[Property in keyof Type]: boolean;
};
type = {
a: string;
b: number;
};
type O = A<FeatureFlags>; // {a:boolean;b:boolean}
这里使用到了泛型, [Property in keyof Type] 会迭代FeatureFlags 所有的key,你也可以让所有的key定义为原来的类型。
type A<Type> = {
[Property in keyof Type]: Type[Property];
};
注意:在映射类型中不能定义属性和方法。
type A<Type> = {
[Property in keyof Type]: Type[Property];
a: string; // 错误
fn:()=>void; // 错误
};