用于超脚本签名的 TypeScript 函数重载
TypeScript function overloading for hyperscript signature
我目前正在尝试使用 typescript 进行更高级的打字,并且想知道如何定义像 hyperscript 中的函数那样的函数。我尝试了各种方法,但无法成功重载 h
函数并使用法注释下列出的所有 CallExpressions 都通过。
这是我目前的情况:
interface IProps {
[key: string]: any;
}
function h(tag: string, props?: IProps): void;
function h(tag: string, children: string): void; // <- marked as invalid
function h(tag: string, props: IProps, children?: string): void {
// ...code goes here
}
用法:
h("div");
h("div", "Hello World");
h("div", { className: "test" });
h("div", { className: "test" }, "Hello World"); // <- marked as invalid
今天早上醒来后我找到了答案。在 TypeScript 中,实现签名对外界不可见,因此调用表达式必须匹配重载之一。
此外,实现签名中的类型必须捕获所有以前的重载。
// Overloads, must match one of these
function h(tag: string, children?: string): void;
function h(tag: string, props: IProps, children?: string): void;
// Not visible for the outside world
function h(tag: string, props: IProps | string, children?: string): void {
// ...
}
我目前正在尝试使用 typescript 进行更高级的打字,并且想知道如何定义像 hyperscript 中的函数那样的函数。我尝试了各种方法,但无法成功重载 h
函数并使用法注释下列出的所有 CallExpressions 都通过。
这是我目前的情况:
interface IProps {
[key: string]: any;
}
function h(tag: string, props?: IProps): void;
function h(tag: string, children: string): void; // <- marked as invalid
function h(tag: string, props: IProps, children?: string): void {
// ...code goes here
}
用法:
h("div");
h("div", "Hello World");
h("div", { className: "test" });
h("div", { className: "test" }, "Hello World"); // <- marked as invalid
今天早上醒来后我找到了答案。在 TypeScript 中,实现签名对外界不可见,因此调用表达式必须匹配重载之一。
此外,实现签名中的类型必须捕获所有以前的重载。
// Overloads, must match one of these
function h(tag: string, children?: string): void;
function h(tag: string, props: IProps, children?: string): void;
// Not visible for the outside world
function h(tag: string, props: IProps | string, children?: string): void {
// ...
}