简体   繁体   English

Typescript:从数组推断类型

[英]Typescript: Infer type from an array

Let's say I have following type:假设我有以下类型:

type TestType = { abc: string }[];

I would like to extract { abc: string } part, but don't know how.我想提取{ abc: string }部分,但不知道如何。

I tried to get first element from tuple, but no luck:我试图从元组中获取第一个元素,但没有运气:

type Head<T extends any[]> = T extends [a: infer A, ...args: any[]] ? A : never;

that approach works for [{ abc: string }] but not for { abc: string }[] although types are the same (I guess?.).该方法适用于[{ abc: string }]但不适用于{ abc: string }[]尽管类型相同(我猜?。)。

Given type TestType = { abc: string }[];给定type TestType = { abc: string }[]; , you can do: , 你可以做:

type ExtractedType = TestType[number]; which is equal to { abc: string }等于{ abc: string }

Moreover, if you need to extract the type of the property abc , you could then do type Foo = ExtractedType["abc"] .此外,如果您需要提取属性abc的类型,则可以执行type Foo = ExtractedType["abc"]

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

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