打字稿:`| 的含义[T]`-用于数组中元素成员资格的编译时检查的约束 [英] TypeScript: Meaning of `| [T]`-constraint for compile-time checks of element membership in arrays
问题描述
我想编写一个函数 f
,它接受 A
类型的单个参数,其中 A
必须是一个包含元素的数组某种类型的T
.为简单起见,假设 T = 'ok'
(字符串 'ok'
的单一类型).
I want to write a function f
that accepts a single argument of type A
, where A
must be an array that contains an element of a certain type T
. For simplicity, assume that T = 'ok'
(singleton type of the string 'ok'
).
使用来自这个答案的想法,我得到了以下初步解决方案:
Using the idea from this answer, I obtained the following preliminary solution:
function f<
E,
A extends (ReadonlyArray<E> | [E]) & {[K in keyof A]: {[T in K]: 'ok'}}[number]
>(a: A) {}
正如上面引用的答案,它确实有效.
As in the answer quoted above, it indeed works.
但我无法理解|[E]
-part,所以我决定检查是否可以删除它,或者用另一种类型替换它:
But I could not make any sense of the | [E]
-part, so I decided to check whether I can remove it, or replace it by yet another type:
function f<
E,
X,
A extends (ReadonlyArray<E> | [X]) & {[K in keyof A]: {[T in K]: 'ok'}}[number]
>(a: A) {}
这也有效,即它可以区分带有或不带有元素 'ok'
的数组:
This also works, i.e. it can differentiate between arrays with or without element 'ok'
:
f(['a', 'b', 'ok', 'z']) // compiles, good
f(['a', 'b', 'z']) // does not compile, good
我的问题是,如果我删除 [X]
部分,我无法理解为什么它不起作用.它似乎与代码中发生的任何事情完全无关:
My problem is that I can't understand why it doesn't work if I remove the [X]
part. It seems completely unrelated to anything what's going on in the code:
[X]
的元数与元组的元数不匹配- 类型
X
实际上并没有绑定到任何东西,它没有包含E
或A
或string<的边界/code> 或
'ok'
或其他任何东西.
- Arity of
[X]
does not match the arity of the tuples - The type
X
isn't actually tied to anything, it has no bounds containing eitherE
orA
orstring
or'ok'
or anything else.
什么是<代码>|[X] 到底在做什么?
What is the | [X]
doing, exactly?
推荐答案
举个简单的例子:
function foo<T extends number[]>(t: T): T { return t }
foo([1, 2, 3]) // number[]
将推断出一个数组返回类型.
will have an array return type inferred.
function foo2<T extends number[] | [number]>(t: T): T { return t }
foo2([1, 2, 3]) // [number, number, number]
<代码>|[编号] 强制 TypeScript 进行推断一个 tuple 而不是数组,不使用 as const
(隐藏的编译器规则,如果你愿意的话).
| [number]
forces TypeScript to infer a tuple instead of an array, without using as const
(a hidden compiler rule, if you will).
您甚至可以通过为扩展基本类型的数组项添加类型参数 R
来保持数字文字的范围:
You can even keep the number literals narrow by adding a type parameter R
for the array items extending a primitive type:
function foo3<R extends number, T extends R[] | [R]>(t: T): T { return t }
foo3([1, 2, 3]) // [1, 2, 3]
这篇关于打字稿:`| 的含义[T]`-用于数组中元素成员资格的编译时检查的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!