typescript 打字稿:从数组类型中检索元素类型信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41253310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: Retrieve element type information from array type
提问by Ben Southgate
Say I have some array type T[]
, is it possible to extract the type T
within another alias / interface? For example my (fake) ideal code would be as follows:
假设我有一些数组类型T[]
,是否可以T
在另一个别名/接口中提取类型?例如,我的(假)理想代码如下:
// for illustration only...
type ArrayElement<T[]> = T;
// then, ArrayElement<string[]> === string
If no, are there general type theory reasons for not allowing such an operator? If no again, I might suggest it be added.
如果不是,是否有不允许这样的运算符的一般类型理论原因?如果没有,我可能会建议添加它。
Thanks!
谢谢!
采纳答案by artem
Since 2.1, typescript supports [ ] operator for types. The official name is indexed access types, also called lookup types, and it works like this:
从 2.1 开始,typescript 支持 [] 操作符作为类型。正式名称是索引访问类型,也称为查找类型,其工作方式如下:
type A = {a: string, b: number} [];
type AElement = A[0];
let e: AElement = {x: 0}; //error TS2322: Type '{ x: number; }' is not
//assignable to type '{ a: string; b: number; }'
回答by Will Madden
You can achieve that with the following:
您可以通过以下方式实现:
type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType[number];
So these examples would work:
所以这些例子会起作用:
type X = ArrayElement<string[]>; // string
type Y = ArrayElement<readonly string[]>; // string
type Z = ArrayElement<[string, number]>; // string | number
Explanation
解释
ArrayType extends readonly unknown[]
says that we expect the type parameter ArrayType
to be at least a readonly array (it also accepts a mutable array) so that we can look at its element type.
ArrayType extends readonly unknown[]
说我们希望类型参数ArrayType
至少是一个只读数组(它也接受一个可变数组),以便我们可以查看它的元素类型。
Note that readonly unknown[]
is syntax added in TypeScript 3.4; for earlier versions use ReadonlyArray<unknown>
.
请注意,这readonly unknown[]
是在 TypeScript 3.4 中添加的语法;对于早期版本,请使用ReadonlyArray<unknown>
.
On the right-hand side, ArrayType[number]
means any value in the array accessible by a numeric index - i.e. any value in the array.
在右侧,ArrayType[number]
表示可通过数字索引访问的数组中的任何值 - 即数组中的任何值。
回答by jerico
Another alternative:
另一种选择:
type ArrayElement<A> = A extends readonly (infer T)[] ? T : never