有没有办法强制 TypeScript 返回某种类型?

时间:2021-07-14 21:20:37

标签: typescript

我有一个通用的“fetcher”功能,如下所述。我遇到的问题是 TypeScript 暗示它的调用代码类型可以是从任何条件返回的任何类型。

是否可以在返回时告诉 TypeScript 仅推断返回的类型?

(initialNotes 和 initialTags 是两种不同的数组类型)

  async function fetcherFunc(entity) {
    await new Promise((resolve) => setTimeout(resolve, 2000));
    if (entity === 'notes') {
      return initialNotes;
    } else if (entity === 'tags') {
      return initialTags;
    }
  }

1 个答案:

答案 0 :(得分:3)

您可以使其返回联合类型 (TypeOfNotesArray | TypeOfTagsArray),或者——如果 entity 将使用编译器时常量指定——您可以使用函数重载:

async function fetcherFunc(entity: "notes"): TypeOfNotesArray;
async function fetcherFunc(entity: "tags"): TypeOfTagsArray;
async function fetcherFunc(entity: "notes" | "tags"): TypeOfNotesArray | TypeOfTagsArray {
    await new Promise((resolve) => setTimeout(resolve, 2000));
    if (entity === 'notes') {
        return initialNotes;
    } else if (entity === 'tags') {
        return initialTags;
    }
    throw new Error(`entity is expected to be "notes" or "tags", but was "${entity}"`);
}

如果您调用 fetcherFunc("notes"),结果将为 TypeOfNotesArray。如果您调用 fetcherFunc("tags"),结果将为 TypeOfTagsArray