typescript - 推断所有值的类型签名

标签 typescript types

这是在 TypeScript 4.0.2 中。类型系统可以从下面示例中的类型签名中推断出一些值。我很困惑为什么它不能推断出 const b 中最后一个元素的具体值。

任何人都可以解释为什么,以及我如何编写可以的类型签名吗?

declare function identityA<T extends string[]>(p: readonly [...T]): T
declare function identityB<T extends any[]>(p: readonly [...T]): [...T]

const a = identityA(['r', 's'])  // ['r', 's']
const b = identityB([...a, 3])  // ['r', 's', number]

最佳答案

TypeScript 的类型推断使用各种启发式方法来确定何时扩大 literal types以及何时让它们尽可能窄。例如,当你写

let s = ""; // string
let n = 0; // number
let b = true; // boolean

变量snb的类型扩展为stringnumberboolean 分别...假设是由于 let 声明允许您重新分配值,因此您可能想要要做到这一点。另一方面,当你写

const sC = ""; // ""
const nC = 0; // 0
const bC = true; // true

变量sCnCbC的类型保持窄为"", 0true。假设是因为您无法更改这些值,所以您没有理由在类型中允许超过这些单个值。


对于类型参数,例如 identityA()identityB() 函数中的 T,编译器会执行其他操作。这在 microsoft/TypeScript#10676 中有所提及:

During type argument inference for a call expression the type inferred for a type parameter T is widened to its widened literal type if (...) T has no constraint or its constraint does not include primitive or literal types

declare function identityA<T extends string[]>(p: readonly [...T]): T

类型参数T有一个constraint包含原始 string 类型,因此 T 不会从 ["r", "s"] 扩大到 [字符串,字符串]。另一方面,在

declare function identityB<T extends any[]>(p: readonly [...T]): [...T]

类型参数 T 的约束不包括任何文字或原始类型,因此 T 将从 [3][数字]。或者由于 "r""s" 类型已经从先前的推断中扩展,T 将从 扩展["r", "s", 3]["r", "s", number].

这很令人困惑,对吧?没关系,使用 variadic tuple type [...T] 在您的 p 参数类型中,您正在向编译器提示您要推断 tuple types对于 T 而不仅仅是数组类型。


这就是它发生的原因。你能做些什么来解决它?

如果您可以控制调用站点,则可以使用 const assertion明确要求编译器为您传入的内容推断最窄的可能类型。这发生在推断 T 之前:

const iBAsConst = identityB([...iA, 3] as const)  // ['r', 's', 3]

但是您问如何更改 signature 以将 identityB() 的类型参数转换为文字偏好的推理事物。您可以通过将 any[] 更改为包含原语的内容来做到这一点。例如:

type Narrowable = string | number | boolean | symbol | 
  object | undefined | void | null | {};
declare function identityC<T extends Narrowable[]>(p: readonly [...T]): [...T]
const iC = identityC(["r", "s", 3]); // ['r', 's', 3] 

几乎任何东西都可以分配给 Narrowable,比如奇怪的 anyunknown 也可以作为 keep-this-narrow 提示.

万岁,对吧?


如果你觉得这一切都是邪恶的魔法,我同意。前段时间我打开了microsoft/TypeScript#30680请求一些语法显式请求函数签名端的类似“as const”的行为。然后你就可以写出类似的东西了

// don't try this, it won't work:
declare function identityB<T extends any[] as const>(p: readonly [...T]): [...T];

获得同样的效果。唉,它只是作为今天(2020-09-24)的建议,所以现在你必须继续练习黑暗艺术以获得你正在寻找的推理。

Playground link to code

关于typescript - 推断所有值的类型签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64056538/

相关文章:

单个序列中的 Angular、ngrx/store、store select 和异步调用

angular - ngx-translate 即时函数不是抛出 : Unit testing 的函数

javascript - TypeScript:在 Enum 上执行 switch-case 来设置变量的惯用方法

typescript - 为什么应该在对象查找中使用 "as keyof typeof lookup"?

C 128 位 double 型

postgresql - 在 PostgreSQL 中找不到函数

reactjs - 如何将react-hooks、redux和typescript结合在一起?

java - 类型不匹配 : cannot convert from ASuperClass to ASubClass

c++ - 有没有办法从 `std::function` 返回到指针?

scala - 在 Scala 中引用内部类的类型