在angular2中承诺的编译时类型安全性

时间:2017-03-10 10:03:14

标签: angular typescript promise angular-cli typescript-generics

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

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"
    ]
  }
}

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

0 个答案:

没有答案