Typescript 在本地函数中类型推断失败

问题描述 投票:0回答:1

我陷入了失败的类型推断,但我不清楚为什么......这是代码:

type A = {
    kind: 'A',
    aaa : string,
}

type B = {
    kind: 'B',
}

type C =
        | A
        | B;

export function test(items: Array<C>) {
    for (let item of items) {
        switch (item.kind) {
        case 'A':
            console.log(item.aaa); // this compiles correctly
            let f = () => {
                console.log(item.aaa); // this gives error:
                // error TS2339: Property 'aaa' does not exist on type 'C'.
                // Property 'aaa' does not exist on type 'B'.
            };
            f();
        }
    }
}

在 switch 语句中,我区分第一种情况下的 or 类型,我管理类型 A; 编译器似乎理解我在做什么,因为 console.log 在 case 之后正确编译;然后,定义一个函数,相同的 console.log 无法编译,给出导致错误 我认为编译器没有在函数 f 的上下文中使用推断类型 (A)... 但我不明白为什么,因为函数是在类型已知为 A 的范围内定义的......有任何线索吗?

谢谢!!

我的 package.json 文件为我提供了以下版本的内容:

    ...
    "ts-node": "^10.9.1",
    "ts-patch": "^3.0.2",
    "typescript": "^5.2.2",
    ...
typescript inference
1个回答
0
投票

这是由于控制流分析中所做的权衡所致。

它在这个著名的问题中:https://github.com/microsoft/TypeScript/issues/9998

© www.soinside.com 2019 - 2024. All rights reserved.