【问题标题】:Typescript function with argument of type property of Interface带有接口类型属性参数的打字稿函数
【发布时间】:2021-11-13 19:25:08
【问题描述】:

有没有办法将接口的属性/键用作函数参数类型?

例如,如果我有一个接口:

interface column{
   id: string,
   title: string,
   description: string
}

我有一个功能:

const replaceColumnProperty = (col: column, property: string, val: string) => {
   col[property] = val;
}

Typescript 抱怨类型字符串与列接口不匹配。

应该是:

const replaceColumnProperty = (col: column, property: 'id' | 'title' | 'description', val: string) => {
   col[property] = val;
}

但是,我的界面有 20 个属性。有没有办法避免为每个接口属性编写一个常量?

【问题讨论】:

    标签: typescript types interface


    【解决方案1】:

    是的,您可以使用the keyof type operator 获取类对象类型的键的union

    const replaceColumnProperty = (col: Column, property: keyof Column, val: string) => {
      col[property] = val; // okay
    }
    

    您也可以从调用方验证它是否以您想要的方式工作:

    const col = { id: "", title: "", description: "" }
    replaceColumnProperty(col, "id", "id"); // okay
    replaceColumnProperty(col, "oops", "oops"); // error!
    // ----------------------> ~~~~~~
    // Argument of type '"oops"' is not assignable to parameter of type 'keyof Column'.
    

    Playground link to code

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 2021-05-10
      • 2021-06-09
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      相关资源
      最近更新 更多