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

我今天早上醒来后找到了答案。在打字稿中,外部世界看不到实现签名,因此调用表达式必须与其中一个过载匹配。

此外,实现签名中的类型必须捕获所有以前的过载。

// 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 {
  // ...
}

最新更新