TypeScript中简单但破坏的三元条件表达式

时间:2018-03-23 17:13:51

标签: typescript promise ternary-operator

TypeScript 2.7允许我这样做:

const promise = Promise.resolve();
promise.then(() => {});

它让我这样做:

const promise = new Promise(() => {});
promise.then(() => {});

那为什么我不能这样做呢?

const promise = true
  ? Promise.resolve()
  : new Promise(() => {});

promise.then(() => {});

此示例也打破了官方的TypeScript PlayGround:

http://www.typescriptlang.org/play/index.html#src=const%20promise%20%3D%20true%0D%0A%20%20%3F%20Promise.resolve()%0D%0A%20%20%3A%20new%20Promise(()%20%3D%3E%20%7B%7D)%3B%0D%0A%0D%0Apromise.then(()%20%3D%3E%20%7B%7D)%3B

这是编译错误:

  

无法调用类型缺少调用签名的表达式。输入'(< TResult1 = void,TResult2 = never>(onfulfilled?:( value:void)=> TResult1 | PromiseLike< TResul ...'没有兼容的呼叫签名。

我可以&#34;修复&#34;通过从promisePromise<void> | Promise<{}>指定Promise<void | {}>的类型来确定错误:

const promise: Promise<void | {}> = true
  ? Promise.resolve()
  : new Promise(() => {});

promise.then(() => {});

为什么?

1 个答案:

答案 0 :(得分:1)

因为您承诺的类型是:

const promise: Promise<void> | Promise<{}>

将其更改为例如:

const promise = true
  ? Promise.resolve()
  : new Promise<void>(() => {}); // Note the explicit generic type parameter.

promise.then(() => {});

这可能是由于可转让性问题,例如:

let x: (a: void) => void = () => { };
let y: (a: {}) => void = () => { };

y = x; // Type '(a: void) => void' is not assignable to type '(a: {}) => void'.
x = y; // Type '(a: {}) => void' is not assignable to type '() => void'.