在打字稿中创建函数类型模板

问题描述 投票:1回答:2

我有一个类似于以下内容的函数,但不太简单:

function foo(arg1?: string | number | boolean, arg2?: number | boolean, arg3?: boolean) {
  // omitted
}

此功能可以通过多种不同方式运行,例如:

foo();
foo(1, true);
foo("", false);
foo(4);
foo(true);
// ..etc

为了使上下文线索/类型定义可读,最好的方法是重载:

function foo();
function foo(name: string);
function foo(age: number);
function foo(nice: boolean);
function foo(name: string, age: number);
function foo(name: string, nice: boolean);
function foo(age: number, nice: boolean);
function foo(name: string; age: number, nice: boolean);
function foo(arg1?: string | number | boolean, arg2?: number | boolean, arg3?: boolean) {
  // omitted
}

// now it'll figure out which overload I'm on, and give easier to read insights

issue是我不仅仅拥有foo。我有foo,bar,qux,baz和其他30个人。写下这一切将是一堵可怕的文字墙。因此,我尝试为所有人创建一种类型,如果不是针对泛型的类型,它将起作用:

// Without generics, this problem would be solved

export const bar = (function(...args: ArgOutline) {
  // omitted
}) as typeof foo

export const qux = (function(...args: ArgOutline) {
  // omitted
}) as typeof foo

export const baz = (function(...args: ArgOutline) {
  // omitted
}) as typeof foo

/// and so on...

我真正想要的是一个大纲函数,该函数具有泛型并且可以产生具有可读性的见解,但是以下代码不起作用:

function Outline();
function Outline(name: string);
function Outline<PROPS>(props: PROPS);
function Outline(name: string props: PROPS);
function Outline<PROPS>(arg1?: string | PROPS, arg2?: PROPS) {
  // omitted
}


// This doesn't work
export const baz = (function(...args: ArgOutline) {
  // omitted
}) as typeof Outline<{a: number}> 

我已经阅读了为什么不能执行此操作(https://github.com/microsoft/TypeScript/issues/204),但似乎仍然有一种方法,只是没有这种方法。

我如何制作一个泛型类型,以产生说出(+N overloads)而不是() => ReallyTerriblyLongName | (name: string) => ReallyTerriblyLongName | (name: string, props: AlsoATerriblyLongName) => ReallyTerriblyLongName | ...etc的见解?

typescript typeof
2个回答
0
投票

从字面上说是从这个床上爬下来的。

function Outline<PROPS>() {

  function out();
  function out(name: string);
  function out(props: PROPS);
  function out(name: string props: PROPS);
  function out(arg1?: string | PROPS, arg2?: PROPS) {
    // omitted
  }

  return out;
}

// Create the outline, then get its type
const bazOutline = Outline<{a: number}>();
export const baz = (function(...args: ArgOutline) {
  // omitted
}) as typeof bazOutline

创建一个返回所需类型的函数的函数。然后从中获取typeof ...仍然需要在野外进行测试,但是我现在正在获取正确的type defs。也许出口会破裂。


0
投票

Try接口(我假设您的返回类型为空):

interface Outline {
    (): void;
    (name: string): void;
    <PROPS>(props: PROPS): void;
    <PROPS>(name: string, props: PROPS): void;
}

export const bar = function(...args: any[]) { } as Outline;

您还可以将通用参数移至接口本身:

interface Outline<PROPS> {
    (): void;
    (name: string): void;
    (props: PROPS): void;
    (name: string, props: PROPS): void;
}

export const bar = function(...args: any[]) { } as Outline<{ a: number }>;
© www.soinside.com 2019 - 2024. All rights reserved.