【发布时间】:2020-05-14 08:48:39
【问题描述】:
我有一个类似以下的函数,但不那么简单:
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
问题是我不只是有 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