gpt4 book ai didi

typescript - 为什么我可以在 Typescript 中创建不可能的交集类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:42:36 26 4
gpt4 key购买 nike

下面的类型定义无法实现,但编译器在定义它时没有给我任何警告。

// No type error
type impossible = 0 & string[] & 'anything'

值不能是数字和字符串[] 以及字符串文字。

  1. 为什么 typescript 允许创建不可能的类型?
  2. 是否存在用于定义无法实现的类型的真正用例?

最佳答案

安德斯海尔斯伯格 provided以下理由:

It is possible to intersect primitive types (e.g. string & number), but it is not possible to actually create values of such types (other than undefined). Because such types can result from instantiation of generic types (which is performed lazily), it is not possible to consistently detect and error on the operations that create the types.

他还在 2015 年 7 月 3 日的评论中说:

An intersection type allows constituent types to be type parameters. Thus, you can write

declare function combine<T, U>(obj1: T, obj2: U): T & U;

This adds important new expressiveness and allows us to better model existing JS idioms. However, since type parameters can be instantiated with any type arguments, we can't upfront check whether an intersection type is "valid". Instead, we must be prepared to intersect any and all types and have "errors" surface as types for which no values are possible (e.g. string & number). You could argue that we should error when we instantiate such a type, but type instantiation in a polymorphic type system is by design heavily deferred (i.e. it happens "just in time") to avoid type explosion and our error reporting would become practically indeterminate if we went that way.

关于typescript - 为什么我可以在 Typescript 中创建不可能的交集类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com