我想让 Typescript 根据第一个参数提供的输入对象来预测函数 doSomethingWithMyArray
中第二个参数的类型。
示例:
interface IPerson {
name: string;
}
let myArr: IPerson[];
// should present a error
doSomethingWithMyArray(myArr, 'key_of_element_in_array')
// should be accepted
doSomethingWithMyArray(myArr, 'name')
我尝试过这个,但显然 keyof
interface IPerson { name: string; }
const a: IPerson = {name: 'A'};
const b: IPerson = {name: 'B'};
const d: IPerson[] = [a,b];
type f = typeof a[];
function doSomethingWithMyArray<T>(arg1: T, arg2: keyof<T[]> ) {
// do something....
}
// should predict 'name'
doSomethingWithMyArray(d, '');
最佳答案
您可以使用keyof T[number]
获取T
的 key :
function doSomethingWithMyArray<
T extends any[]
>(arg1: T, arg2: keyof T[number] ) { }
您还必须将 T
限制为带有 T extends any[]
的数组。否则,TypeScript 将不允许使用 T[number]
表示法,因为 T
可以是任何内容。
关于typescript - 如何根据提供的对象推断函数调用中 keyof 数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72199248/