用于超文本签名的TypeScript函数重载

时间:2016-12-02 22:45:17

标签: typescript overloading typescript-typings hyperscript

我目前正在涉及打字稿中更高级的打字,并且想知道如何定义类似于来自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

1 个答案:

答案 0 :(得分:0)

今天早上起床后我找到了答案。在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 {
  // ...
}