
typescript中使用变量作为索引来访问未知类型,例如泛型对象成员时,会报错TS7053
function doSomething<T>(obj: T, prop: string) {
obj[prop] // 报错TS7053
}报错如下:
TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘unknown’. No index signature with a parameter of type ‘string’ was found on type ‘unknown’.
function doSomething<T>(obj: T, prop: keyof T) {
obj[prop]
}type Point = { x: number; y: number };
type P = keyof Point;type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish; 下例中变量M相当于类型 string | number
type Mapish = { [k: string]: boolean };
type M = keyof Mapish;参考官方文档