typescript - 如何根据提供的对象推断函数调用中 keyof 数组的内容

标签 typescript

我想让 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 可以是任何内容。

Playground

关于typescript - 如何根据提供的对象推断函数调用中 keyof 数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72199248/

相关文章:

typescript + Vue.js : Property 'xxx' does not exist on type 'never'

Typescript - 如何使用通用定义中的完整类型?

javascript - 无法推送嵌套数组中子级的数据子级

javascript - 使用 WebPack 和 Babel 组合、缩小并转换为 ES5

reactjs - 类型 'string' 不可分配给类型 '"inherit"| "initial"| "unset"| "fixed"| "absolute"| "static"| "relative"| "sticky"'

javascript - 分层 react View 中的状态传播

javascript - Nightmare.js 未处理的 promise 拒绝

typescript - @typescript-eslint/命名约定 : How to mix error and warn rules?

css - 使用范围变量时 ngStyle 绑定(bind)不起作用

angular - 如何让我的 Angular 6 组件继承其扩展组件的样式?