0

使用 ng cli 创建的新项目。当使用 "ng serve" 编译/服务时,编译过程不会捕获 Promise 的通用参数上的类型错误。而是为我自己的泛型类型抛出错误(如预期的那样)。

export class MyThing<T> {
    thing: T;

    constructor(t: T) {
        this.thing = t;
    }
}

// throws an error (expected, MyThing<number> is not assignable to MyThing<string>)
export function throwsAsExpected(): MyThing<string> {
    return new MyThing<number>(4);
}

// DOESNT throw an error (I expected, Promise<number> is not assignable to Promise<string>)
// maybe there's something 
export function doesntThrow(): Promise<string> {
    return new Promise<number>((resolve, reject) => {
        resolve(42);
    });
}

对于上面的代码,我得到了这个:

ERROR in E:/src/poc-gui/src/app/services/ws/whatever.service.ts (20,9): Type 'MyThing<number>' is not assignable to type 'MyThing<string>'. Type 'number' is not assignable to type 'string'.)

这是预期的,但它没有捕捉到 promise 函数的错误。令人怀疑的是,Sublime(带有 ts 插件)按预期显示错误。

我的 tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "es5",
    "noEmitOnError": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "strictNullChecks": false,
    "lib": [
      "es2016"
    ]
  }
}

是否可以为承诺保留编译时类型安全性,或者我错过了什么?

4

0 回答 0