如果我想希望使用某种类型声明的子类型作为某个变量声明的类型…
typescript">export interface Car {
Name: string;
Speed: number;
Manufactured: number;
}
const Speed: Car.Speed = 200;
上面的写法会抛出错误
Cannot access ‘Car.Speed’ because ‘Car’ is a type, but not a namespace. Did you mean to retrieve the type of the property ‘Speed’ in ‘Car’ with ‘Car[“Speed”]’
这是因为你的使用姿势不对。需要用如下的写法
typescript">const Speed: Car['Speed'] = 200;
这种类型称为Lookup Types
这种使用某种类型的"成员类型"作为类型声明的使用有两种方式:
typescript">interface Person {
name: string;
age: number;
location: string;
}
type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person }; // string
或者
typescript">type P1 = Person["name"]; // string
type P2 = Person["name" | "age"]; // string | number
type P3 = string["charAt"]; // (pos: number) => string
type P4 = string[]["push"]; // (...items: string[]) => number
type P5 = string[][0]; // string
参考:
https://stackoverflow.com/questions/55607608/how-can-i-reuse-a-type-of-an-interface-member