keyof typeof
是什么意思
keyof
作用于 object
类型,并返回这个 object
的 key
的集合类型:
1
2
|
type Point = { x: number; y: number };
type P = keyof Point; // type '"x" | "y"'
|
typeof
操作符作用于 JavaScript 对象和作用于 TypeScript 类型的时候结果是不一样的:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
const obj = {
name: "aaa",
key: "bbb",
};
type ObjType = typeof obj;
// type ObjType = { name: string; key: string; }
const newObj: ObjType = {
name: 1111, // Type 'number' is not assignable to type 'string'.
};
console.log(typeof obj); // "object"
|
所以 keyof typeof
就是获取 JavaScript 对象的 key
的集合。
几个内置类型
Record<Keys, Type>
创建一个 key
类型是 Keys
,value
类型是 Type
的对象类型。
1
2
3
4
5
6
7
8
9
10
11
12
|
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
|
ReturnType<Type>
返回函数 Type
的返回类型。
1
2
3
4
5
6
7
8
9
10
|
type Fn = () => { a: number; b: number };
type Type1 = ReturnType<Fn>; // {a: number, b: number}
function fn() {
return { a: 1, b: 2 };
}
type Type2 = ReturnType<fn>; // fn refers to a value, but is being used as a type here. Did you mean 'typeof f'?
type Type2 = ReturnType<typeof fn>; // {a: number, b: number}
|
参考资料