我将打字稿从3.4.1升级到3.7.4后出现编译错误

时间:2020-01-09 12:33:47

标签: typescript

这是我的tsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "outDir": "dist",
        "module": "commonjs",
        "target": "es6",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
       "sourceMap": true
    }
}

以下是重现该错误的代码:

async function f1(): Promise<{a: number}> {
    return Promise.resolve({} as any);
}

async function f2(): Promise<{a: number, b: number}> {
    return Promise.resolve({} as any);
}

(async ()=> {
    const tp = await Promise.all([f1(), f2()]);
    let a = tp[0].a;
    let b = tp[1].a;
    let c = tp[1].b;
    console.log(a, b, c);
})();

错误是:

错误:(13,19)TS2339:类型'{a上不存在属性'b' 数; }'。

1 个答案:

答案 0 :(得分:1)

Promise。由于更高版本中引入了一些错误,因此所有类型都无法正确推断类型,这是一种解决方法。

type PromiseOne = {
    a: number;
}

type PromiseTwo = {
    a: number;
    b: number;
}

function f1(): Promise<PromiseOne> {
    return Promise.resolve({ a: 1 });
}

function f2(): Promise<PromiseTwo> {
    return Promise.resolve({ a: 1, b: 2 });
}

(async () => {
    const tp = await Promise.all<PromiseOne, PromiseTwo>([f1(), f2()]);
    let a = tp[0].a;
    let b = tp[1].a;
    let c = tp[1].b;
})();

请参阅:https://github.com/microsoft/TypeScript/issues/34925