简体   繁体   English

TypeScript:类型推断不正确

[英]TypeScript: Incorrect type inference

Stumbled upon an incorrect type inference.偶然发现了不正确的类型推断。 Perhaps, when checking the type, the depth of traversal of complex structures is limited?也许,在检查类型时,复杂结构的遍历深度是有限的?

TypeScript version: 4.1.5 TypeScript 版本:4.1.5

type ZERO = 0
type Next<T> = T extends ZERO ? {v: ZERO} : (T extends {v: infer U} ? {v: Next<U>} : never)

type ONE = Next<ZERO>
type TWO = Next<ONE>
type THREE = Next<TWO>
type FOUR = Next<THREE>
type FIVE = Next<FOUR>
type SIX = Next<FIVE>
type SEVEN = Next<SIX>
type EIGHT = Next<SEVEN>
type NINE = Next<EIGHT>
type TEN = Next<NINE>

type TEq<T, P> = T extends P ? (P extends T ? true : never) : never

let v1:TEq<TWO, TWO> = true // correct: types is equal
let v2:TEq<TWO, THREE> = true // correct: type 'boolean' is not assignable to type 'never'
let v3:TEq<SIX, EIGHT> = true // error: why type of v3 inferred as true?

Playground link 游乐场链接

Here you can find Microsoft build talk. 在这里您可以找到 Microsoft 构建演讲。

This comment explains design limitation 此评论解释了设计限制

it's a recursion guard to prevent literally infinite computation.它是一种递归保护,可以防止字面上的无限计算。 If S needs to compare itself to S<S> to determine assignability, and then S<S> needs to compare itself to S<S<S>>, then S<S<S>> needs to compare itself to S<S<S<S>>>, then S<S<S<S>>> needs to compare itself to S<S<S<S<S>>>>, at that point the checking stops and it's assumed that the answer is "yes".如果 S 需要将自己与 S<S> 进行比较以确定可分配性,然后 S<S> 需要将自己与 S<S<S>> 进行比较,那么 S<S<S>> 需要将自己与 S<S 进行比较<S<S>>>,然后 S<S<S<S>>> 需要将自己与 S<S<S<S<S>>>> 进行比较,此时检查停止并假定答案是是的”。 This case actually does come up in practice quite a bit;这种情况实际上在实践中确实出现了很多。 if your model is dependent on this checking going arbitrarily deep, then effectively you're asking for the compiler to sometimes freeze forever checking S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S>>>>>>>>>>>>>>>>>>>>>>>> against S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S>>>>>>>>>>>>>>>>>>>>>>>>> (which in turn will check S<SS<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S>>>>>>>>>>>>>>>>>>>>>>>>>>.如果您的 model 依赖于这种任意深度的检查,那么实际上您要求编译器有时永远冻结检查 S<S<S<S<S<S<S<S<S<S<S<S< S<S<S<S<S<S<S<S<S>>>>>>>>>>>>>>>>>>>>>>>>反对S<S<S<S< S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S>>>>>>>>>>>>>>>> >>>>>>>>>>(依次检查 S<SS<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S< S<S<S<S<S>>>>>>>>>>>>>>>>>>>>>>>>>>。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM