【问题标题】:How to define a function's argument type as one of the keys (or properties) of an interface如何将函数的参数类型定义为接口的键(或属性)之一
【发布时间】:2022-09-23 02:13:25
【问题描述】:

给定任何接口,有没有办法说变量的类型是该接口中的键之一?

假设你有这个界面:

interface IExample {
  a: string;
  b: {
    b1: string;
    b2: string | number | boolean;
  };
}

你有一个像这样的功能:

const function = (arg) => {
  //function\'s logic 
}

现在我想从IExample 输入argb,类似于:

const function = (arg: IExample.b): void => {
  //function\'s logic 
}

需要明确的是,函数的参数应该是:

{
  b1: string;
  b2: string | number | boolean;
}

而且我不想为此编写另一个接口。

我自己找不到方法,也没有通过阅读打字稿文档来弄清楚。这是我最后的希望。

    标签: typescript typing


    【解决方案1】:

    您使用[] 来索引类型。

    function foo(arg: IExample['b']): void {
      //function's logic 
    }
    
    foo({ b1: 'abc', b2: true })
    

    See Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2017-11-24
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多