繁体   English   中英

如何将函数的参数类型定义为接口的键(或属性)之一

[英]How to define a function's argument type as one of the keys (or properties) of an interface

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

假设你有这个界面:

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

你有一个 function 像:

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

现在我想从IExamplearg输入为b ,例如:

const foo = (arg: IExample.b): void => {  // this generates an error
  //function's logic 
}

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

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

而且我不想为此编写另一个界面。

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

您使用[]来索引类型。 一些关于此的文档是here。

function foo(arg: IExample['b']): void {
  //function's logic 
}

foo({ b1: 'abc', b2: true })

见游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM