英文:
In simple english can anyone explain why and when to use the never type?
问题
我一直在努力理解何时使用"never"类型,所以有人可以解释并提供一些何时使用"never"类型的情况吗?我已经读过关于它在无限循环等情况下的用法,但仍然不太明白。有人可以解释何时使用"never"类型以及在什么场景下使用吗?
我无法理解这个概念,我已经试过阅读博客和文章,我只是不明白应该在哪里使用它。
英文:
I've been struggling to understand when to use the never type, so can anyone explain and give some scenarios when to use the never type? I've read about it being use in endless loops and stuff but, still don't quite get it. can anyone explain when to use the never type and in what scenario?
I couldn't wrap my head around the concept, I've tried reading blogs and articles, I just can see where should i use it.
答案1
得分: 1
你可以更幸运地放弃试图找到 never
的原因,简单地利用游戏规则。never
用于各种不同原因,它是一个多用途工具。在进行类型级别编程时,随着进行下去,你会找到使用案例。
属性:
never
扩展了一切- 只有
never
和any
扩展到never
never & T
是never
never | T
是T
一些特殊情况:
any extends never ? X : Y
是X | Y
[any] extends [never] ? X : Y
是Y
- 如果
T
是never
,T extends U ? X : Y
是never
[T] extends [U] ? X : Y
取决于U
,会得到你期望的结果
利用这些属性的一种方式示例:知道 never | T
是 T
,如果你正在构建一个联合类型并且想要过滤掉其中的一些成员,你会有意地生成 never
值,期望它们稍后会被吞噬。
对于面向用户的类型,一个经验法则是简单地避免将 never
和 any
用作值,而将它们用作约束或参数类型。然后,never
就成为一种便宜的方式来禁止某个值。例如:
- 如果你想要禁止包含键
foo
的对象:将{ foo?: never }
作为约束或参数类型。 - 如果你想要拒绝某些输入,但无法想出类型定义:编写一个实用类型,在输入不满足要求时返回
never
:<A extends Check<A>>(a: A) => whatever
(其中Check<T>
可能会返回never
)
英文:
You may have more luck if you give up trying to find a reason for never
and simply exploit the rules of the game. never
is used all over the place for different reasons, it is a multi-purpose tool. You will find use cases as you go when doing type-level programming.
Properties:
never
extends everything- only
never
andany
extendnever
never & T
isnever
never | T
isT
Some quirks:
any extends never ? X : Y
isX | Y
[any] extends [never] ? X : Y
isY
T extends U ? X : Y
isnever
ifT
is never[T] extends [U] ? X : Y
is what you expect depending onU
An example of a way to exploit these properties: knowing that never | T
is T
, if you are constructing a union and you want to filter out some of its members, you will intentionally produce never
values expecting that they will be swallowed later.
For user-facing types, a rule of thumb is simply to avoid using never
and any
as values, but to use them as constraints or parameter types. never
then becomes a cheap way to forbid a value. For example:
- if you want to forbid objects containing the key
foo
: write{ foo?: never }
as a constraint or parameter type. - if you want to reject certain inputs but you can't think of a type definition: write a utility type that returns
never
when the input doesn't meet your requirements:<A extends Check<A>>(a: A) => whatever
(whereCheck<T>
may returnnever
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论