在Typescript中,当数组包含不同的元素类型时,如何从数组类型中获取元素类型?

mas*_*dus 5 typescript

假设我有一个不同类型的数据数组:

const input = ["random", 2, {a: "foo", b: "baz"}];
Run Code Online (Sandbox Code Playgroud)

Typescript可以自动推断和提取类型,例如:

type InputTypeArray = typeof input;
Run Code Online (Sandbox Code Playgroud)

这里的打字稿知道InputTypeArray是(string | number | {a:string,b:string})[];

让我们将InputType称为数组元素的类型,即:

typeof InputType = string | number | {a: string, b: string};
Run Code Online (Sandbox Code Playgroud)

我可以从InputTypeArray派生InputType吗?换句话说,我将如何编写一个接受输入元素之一作为参数的函数?

const input = ["random", 2, {a: "foo", b: "baz"}];

const myFunction = (element: InputType) => element;

input.map(myFunction);
Run Code Online (Sandbox Code Playgroud)

我如何在这里写“ InputType”?有没有办法从输入中提取出来?

我知道我可以通过在map调用中内联myFunction来解决,因为打字稿会再次推断函数内的正确类型。但是有没有办法获得这种类型呢?

Jam*_*ren 16

您可以使用此格式获取成员类型:

type InputType = typeof input[number];
Run Code Online (Sandbox Code Playgroud)

你可以阅读更多关于它(和其他一些很酷的技巧),这里的史蒂夫Holgado酒店的博客文章。

  • 对我来说,这种通用方法似乎比显式使用索引(如另一个解决方案中给出的“input[0]”)更好,因为当数组为空时它不会失败。 (2认同)

Fen*_*ton 5

您可以通过指向数组成员来提取它,因此在使用以下代码获取数组类型时:

type A = typeof input;
Run Code Online (Sandbox Code Playgroud)

您可以使用它来获取单个项目的类型:

type B = typeof input[0];
Run Code Online (Sandbox Code Playgroud)

  • 您还可以执行“type B = typeof input[number]” (5认同)
  • 最后这非常微不足道:)出于某种原因,我期望 typeof input[0] 会返回字符串,因为这是第一个元素的类型,但显然它在类型级别没有意义。谢谢! (2认同)