映射到 Typescript 接口时如何保留函数重载[重复]

问题描述 投票:0回答:0

代码

想象一个具有两个函数重载的接口。

interface Api {
  parseNumber(input: string, useBigInt: true): bigint
  parseNumber(input: string, useBigInt: false): number
}

你如何映射这些函数来创建一个新的接口,每个函数都有异步版本?

{
  parseNumber(input: string, useBigInt: true): Promise<bigint>
  parseNumber(input: string, useBigInt: false): Promise<number>
}

我试过的

您可以轻松地提取函数名称的并集,函数签名的并集,但是当您要求返回类型的并集时,您只能得到声明顺序中的最后一个。

type TMethodNames = keyof Api; // GOOD: `parseNumber`
type TMethodImplementations = Api[keyof Api]; // GOOD: both signatures
type TMethodReturns = ReturnType<TMethodImplementations> // BAD: only `number` rather than `number | bigint`

尝试通过映射生成新接口会导致除最后一个函数签名外的所有函数签名都被删除。

type AsyncApi = {
  [TMethodName in keyof Api]: (...args: Parameters<Api[TMethodName]>) => Promise<ReturnType<Api[TMethodName]>>
};

const asyncApi = null as unknown as AsyncApi;
asyncApi.parseNumber('123', false); // GOOD: return type is `Promise<number>`
asyncApi.parseNumber('123', true); // BAD: signature is completely missing
javascript typescript overloading mapped-types keyof
© www.soinside.com 2019 - 2024. All rights reserved.