小编inf*_*ctr的帖子

在没有判别的情况下缩小打字稿中的条件类型

我有一个简单的 api 调用函数,它可以获取数据并根据参数标志有条件地映射结果。

作为获取结果,我得到了条件类型或联合类型,但我无法在这里使用类型保护,因为这两种类型不共享共同的可区分属性,并且我应该根据外部来区分它们类型。我如何告诉打字稿这两种类型依赖于另一种类型?是不是这样就需要再添加一层间接层呢?

// prerequisites
declare function apiService(...a: any[]): any;
declare function mapExternalFoo(x: IExternalFoo): IFoo;
declare function mapExternalBar(x: IExternalBar): IBar;
interface IFoo { a: any; }
interface IBar { b: any; }
interface IExternalFoo { c: any; }
interface IExternalBar { d: any; }

interface IProps<T extends boolean> {
  isExtended?: T;
}

// I want it to look like this, but it fails with a compile error

function fetchData<T extends boolean>(params: IProps<T>): Promise<T extends true ? IFoo : IBar> …
Run Code Online (Sandbox Code Playgroud)

typescript

7
推荐指数
1
解决办法
1256
查看次数

标签 统计

typescript ×1