小编Jus*_*ple的帖子

使用对象重载 Typescript 函数 - 重载的实现签名在外部不可见

问题

如何正确公开重载实现签名?

例子

基于这个问题

interface MyMap<T> {
  [id: string]: T;
}

type Options = {
  asObject?: boolean,
  other?: Function
  testing?: number
};


function get(options: { asObject: true, other?: Function, testing?:number }): MyMap<any>;
function get(options: { asObject?: false,  other?: Function, testing?:number }): number[];
function get(): any[];
function get(options: Options = { asObject: false }): any[] | MyMap<any> {
    if (options?.asObject) return {} as MyMap<any>;

    return [];
}

Run Code Online (Sandbox Code Playgroud)

如何包装此函数但根据选项参数保留可能的返回类型?

例如:

function wrapFunction(arg1 arg2, options) { 
   // do something with arg1 …
Run Code Online (Sandbox Code Playgroud)

generics overloading object signature typescript

6
推荐指数
1
解决办法
3718
查看次数

标签 统计

generics ×1

object ×1

overloading ×1

signature ×1

typescript ×1