通过类型推断写出 T[Key]
ts
function getPropValue<T extends object, Key extends keyof T>(obj: T, key: Key): T[Key] {
return obj[key];
}
这里的 Key in keyof T 取出来是Type 'Key' is not assignable to type 'string | number | bigint | boolean | null | undefined'.
需要要用交叉类型做合并;
ts
type MapType<T> = {
[
Key in keyof T
as `${Key & string}${Key & string}${Key & string}`
]: [T[Key], T[Key], T[Key], T[Key]]
}
type res = MapType<{a: 1, b: 2}>;