在通用类型中创建可选参数

Create Optional Parameters in Generic Type

我自己并没有完全处理 typescript 问题,但是我不止一次遇到过对具有不同参数的泛型类型的需求,因为我不太了解这个主题,所以我决定离开题 任务看起来很简单:

interface sampelType{
    typeOne: (arg1:number,arg2:customType) => 0 | Promise<any>
    typeTwo: (arg1:string) => 0 | Promise<any>
    typeThree: () => 0 | Promise<any>
}

我想抓住这个机会:

const caseOne:sampelType<number,customType>;
const caseTwo:sampelType<string>;
const caseThree:sampelType;

The generic type "sampelType" requires the following number of type arguments: 1.

我更想实现这样的类型特性,但我不明白如何做一个可选类型,可能是重载,但我还没有找到方法:

type simpelType<T1, T2> = (arg1?: T1, arg2?: T2) => 0 | Promise<any>;

可能就这些了,对于 TypeScript 中干净代码的其他方法的任何建议或观点,我将很高兴

所以在一般情况下,您可以通过为它们提供默认值来使泛型可选:

type simpelType<T1 = string | number, T2 = {}> = (arg1?: T1, arg2?: T2) => 0 | Promise<any>;

但根据您的示例代码,您可能想要更像这样的东西:

function foo(): 0 | Promise<any>
function foo(x: string): 0 | Promise<any>
function foo<T>(x: number, y: T): 0 | Promise<any>
function foo<T>(x?: string | number, y?: T): 0 | Promise<any> {
  // do stuff
  return 0
}

foo()           // fine, matches overload 1
foo('hi')       // fine, matches overload 2
foo(3, true)    // fine, matches overload 3 T is inferred as boolean

foo(3)          // error!
foo('hi', true) // error!

抱歉,语法突出显示有点不对劲,但这是 highlight.js 中的一个已知错误,Stack Overflow 将其用于语法突出显示。

请注意,尽管编译器将通过解析特定的重载来确保类型安全,但您的代码仍然必须弄清楚您在函数体中得到的是哪一个:

function foo(): 0 | Promise<any>
function foo(x: string): 0 | Promise<any>
function foo<T>(x: number, y: T): 0 | Promise<any>
function foo<T>(x?: string | number, y?: T): 0 | Promise<any> {
  if (typeof x === 'number') {
    // here you know y exists and you're in overload #3
  } else if (typeof x === 'string') {
    // here you are in overload #2
  } else { // no arguments
    // overload #1
  }
  return 0
}

Playground link