gpt4 book ai didi

TypeScript:类型推断不正确

转载 作者:行者123 更新时间:2023-12-05 06:50:46 25 4
gpt4 key购买 nike

偶然发现了不正确的类型推断。也许,在检查类型时,复杂结构的遍历深度有限?

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你可以找到 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>>>>>>>>>>>>>>>>>>>>>>>>>>.

关于TypeScript:类型推断不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66346104/

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