【问题标题】:Return union type causing typescript not to compile返回联合类型导致打字稿无法编译
【发布时间】:2019-01-09 18:56:12
【问题描述】:

我有一个返回联合类型的函数:

   export const getCarMakes = (year: number): Promise<IMakes |IErrorResponse> => {
  return fetch(
    'url', {
      method: 'GET',
    })
  .then((res: Response) =>  res.json())
  .then((data: IMakes | IErrorResponse) => data)
  .catch((error: any) => {
    throw new Error(error);
  });
};

带接口:

interface IMakes {
  makes: string [];
}

interface IErrorResponse {
  code: number;
  msg: string;
}

此刻 VS 代码在抱怨

Property 'code' does not exist on type 'IMakes | IErrorResponse'.
Property 'code' does not exist on type 'IMakes'.

我认为我遗漏了一些东西,因为我可以从 API 获得 2 个完全不同的响应,这些响应可以是带有项目数组的有效响应,也可以是带有消息的错误。我该如何解决这个问题

【问题讨论】:

  • 这很好export const getMakes = (year: number): Promise&lt;IMakes | IErrorResponse&gt; =&gt; Promise.resolve({ code: 0, msg:"" }),你能发布更多代码吗?
  • 你能展示你的函数的实现吗?

标签: javascript typescript


【解决方案1】:

我之前遇到过这个问题,我修复它的方法是在返回任何内容之前检查函数返回的内容。

以这个函数为例

interface Foo {
    foo: string;
}

interface Bar {
    bar: boolean;
}

async function fooBar(): Promise<Foo | Bar> {
    try {
        const response = await asyncFn();

        return Promise.resolve({ foo: '' })
    } catch (err) {
        return Promise.reject({ bar: false });
    }
}

此函数可以返回 FooBar,但由于返回取决于 try/catch 中发生的情况,因此如果一个案例通过但另一个案例不通过,TypeScript 将不会对两者进行类型检查。

所以在做的时候:

fooBar()
  .then(console.log)
  .catch(console.error);

TypeScript 不会抛出 TypeError,因为函数的返回取决于使函数能够返回两个值的逻辑。

这是我的意思TypeScript playground 的示例实现。我几乎 100% 确定 TypeScript 只会在你有 strictFunctionTypes 选项时才会抱怨。

希望这已经足够清楚了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2021-08-05
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多