【问题标题】:Typescript not throwing error on wrong promise return type打字稿不会在错误的承诺返回类型上抛出错误
【发布时间】:2017-03-18 02:50:08
【问题描述】:

使用Typescript 2.0.7


当使用q Promises 时,即使在声明函数的已定义返回类型或什至各自的 then 时,只要函数可能返回 null,任何类型限制都会被取代,并且错误的解析类型不会抛出任何错误。

import Q = require('q');

class Foo {
  prop1: string;
  prop2: number;
}

function test () : Q.IPromise<Foo>
{
  return Q.resolve('stuff')
    .then<Foo>(() =>
    {
      if(Math.random() > 0.5)
      {
        return Q.resolve({ id: 3, value: new Foo() }) // This should throw an error
      }
      else
      {
        return Q.resolve(null);
      }
   });
}

此外,当尝试使用 ES6 Promises 测试相同的行为时,以下代码也没有抛出错误。

function test(): Promise<Foo>
{
   return new Promise((resolve, reject) => {
    resolve('foo');
   })
}

有人可以解释这种行为以及如何获得正确的错误,或者这是 TypeScript 的错误吗? (我见过多个描述类似情况的问题,但没有一个能真正解释这种行为)

【问题讨论】:

    标签: typescript compiler-errors null promise q


    【解决方案1】:

    当您返回非泛型Promise 时,它实际上会被解释为Promise&lt;{}&gt;,可以分配给Promise&lt;Foo&gt;。为什么它现在在resolve 上抛出错误,它可能是任何东西。

    你的代码应该是这样的强类型。

    function test(): Promise<Foo>
    {
       return new Promise<Foo>((resolve, reject) => {
        resolve('foo'); //compile error here
       })
    }
    

    【讨论】:

    • 这就是我所担心的,因为它为错误留下了空间。对第一个有任何想法吗?
    • 没用过Q,但是根据typing,推断出承诺的泛型类型是resolve方法。所以应该是Q.resolve&lt;Foo&gt;
    • True - 幸运的是,仅在 null 上使用它就足够了,就像 Q.resolve&lt;Foo&gt;(null) 一样解析(否则它会解析为 Promise&lt;any&gt;),但仍然存在相当大的问题,因为 TS 不能保证函数返回类型确实与实际返回值匹配。
    • 再想一想,为什么Promise&lt;{}&gt; 可以分配给Promise&lt;Foo&gt;{} 毕竟不能分配给Foo
    • 这是因为当前的Promise 定义。问题在这里github.com/Microsoft/TypeScript/issues/9953
    猜你喜欢
    • 2020-08-27
    • 2021-08-21
    • 1970-01-01
    • 2019-04-25
    • 2016-01-22
    • 2017-11-25
    • 1970-01-01
    • 2017-03-15
    • 2023-03-16
    相关资源
    最近更新 更多