本篇整理自 TypeScript Handbook 中 「Indexed Access Types」 章节
indexed Access Type
我们可以使用 索引访问类型(indexed access type) 查找另外一个类型上的特定属性
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
// type Age = number
// 因为索引名本身就是一个类型,所以我们也可以使用联合、keyof 或者其他类型
type I1 = Person["age" | "name"];
// type I1 = string | number
type I2 = Person[keyof Person];
// type I2 = string | number | boolean
type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];
// type I3 = string | boolean
接下来是另外一个示例,我们使用 number 来获取数组元素的类型。结合 typeof 可以方便的捕获数组字面量的元素类型:
const MyArray = [
{ name: "Alice", age: 15 },
{ name: "Bob", age: 23 },
{ name: "Eve", age: 38 },
];
type Person = typeof MyArray[number];
// type Person = {
// name: string;
// age: number;
// }
type Age = typeof MyArray[number]["age"];
// type Age = number
作为索引的只能是类型,这意味着你不能使用 const 创建一个变量引用:
const key = "age";
type Age = Person[key]; // error
type Age = Person[typeof key]; // success
实例
假设有这样一个业务场景,一个页面要用在不同的 APP 里,根据所在 APP 的不同,调用的底层 API 会不同、
// type APP = ['App1', 'App2', 'App3'] --- tuple类型
const APP = ['App1', 'App2', 'App3'] as const;
// type app = "App1" | "App2" | "App3"
type app = typeof APP[number];
function getPhoto(app: app) {
// ...
}
getPhoto('App1'); // ok
getPhoto('whatever'); // not ok