用索引访问类型查找另外一个类型上的特定属性
使用typeof获取数组类型,使用number获取数组元素类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const MyArray=[ { name: "Alice", age: 15 }, { name: "Bob", age: 23 }, { name: "Eve", age: 38 }, ]; type Person=typeof MyArray;
type Person1=typeof MyArray[number];
type Age=typeof MyArray[number]["age"];
type Age2=Person["age"];
|
什么情况下可以用T[string]
1 2 3 4 5
| interface NumberRecord { [key: string]: number; }
type PropType = NumberRecord[string];
|
这里使用string这个类型访问NumberRecord,由于其内部声明了数字类型的索引签名,这里访问到的结果即是number类型
1 2 3 4 5 6
| interface Foo { propA: number; propB: boolean; propC: string; } type PropTypeUnion = Foo[keyof Foo];
|
这里将联合类型每个分支对应的类型进行访问后的结果,重新组成联合类型
在未声明索引签名类型的情况下,我们不能使用NumberRecord[string]这种原始类型的访问方式,而只能通过键名的字面量类型来进行访问
1 2 3 4 5 6
| interface Foo { propA: number; }
type PropAType = Foo[string];
|
Array中为什么不能使用Array[string],可以使用Array[length]?
1 2
| type Colors = ["white", "red", "black", "purple"] type ColorsString = Colors[string]
|
原因是:
- array没有string索引签名
- T[length]因为他有一个特定的字符串可以使用
- string或number表示所有字符和数字,但这需要索引签名
参考:
https://ts.yayujs.com/handbook/IndexedAccessTypes.html#%E7%B4%A2%E5%BC%95%E8%AE%BF%E9%97%AE%E7%B1%BB%E5%9E%8B-indexed-access-types
https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html