简体   繁体   中英

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

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.

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". 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>>>>>>>>>>>>>>>>>>>>>>>>>>.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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