打字稿:从数组类型中检索元素类型信息 [英] Typescript: Retrieve element type information from array type
问题描述
假设我有一些数组类型 T[]
,是否可以在另一个别名/接口中提取类型 T
?例如,我的(假)理想代码如下:
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:
// 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.
谢谢!
推荐答案
更新:基于@jerico 在下面的回答
以下类型别名将返回数组或元组中元素的类型:
The following type alias will return the type of the elements in an array or tuple:
type ArrayElement<ArrayType extends readonly unknown[]> =
ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
所以这些例子会起作用:
So these examples would work:
type A = ArrayElement<string[]>; // string
type B = ArrayElement<readonly string[]>; // string
type C = ArrayElement<[string, number]>; // string | number
type D = ArrayElement<["foo", "bar"]>; // "foo" | "bar"
type E = ArrayElement<(P | (Q | R))[]>; // P | Q | R
type Error1 = ArrayElement<{ name: string }>;
// ^^^^^^^^^^^^^^^^
// Error: Type '{ name: string; }' does not satisfy the constraint 'readonly unknown[]'.
说明
类型保护(尖括号中的位)ArrayType extends readonly unknown[]
表示我们期望类型参数 ArrayType
至少是一个只读数组(它还接受一个可变数组)以便我们可以查看它的元素类型.
The type guard (the bit in the angle brackets) 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.
这可以防止传入非数组值,如最后一个示例中所示,它可以防止 ArrayElement
永远返回 never
.
This prevents passing in a non-array value, as in the final example, which prevents ArrayElement
ever returning never
.
注意 readonly unknown[]
是 TypeScript 3.4 添加的语法;对于早期版本,使用 ReadonlyArray
.
Note that readonly unknown[]
is syntax added in TypeScript 3.4; for earlier versions use ReadonlyArray<unknown>
.
在右侧,条件表达式要求编译器在模式 readonly ElementType[]
中填写 ElementType
的值并返回 ElementType
如果可以,或者 never
如果不能.
On the right-hand side, the conditional expression asks the compiler to fill in the value of ElementType
in the pattern readonly ElementType[]
and return ElementType
if it can, or never
if it can't.
由于开头的类型保护意味着我们只会传递一个与此模式匹配的值,因此它保证始终匹配并且永远不会返回never
.
Since the type guard at the beginning means we will only ever be passed a value which matches this pattern, it's guaranteed always to match and never to return never
.
上一个回答
type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType[number];
这篇关于打字稿:从数组类型中检索元素类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!