0

我目前在打字稿中涉及更高級的打字類型,並且想知道如何定義像來自hyperscript的函數那樣的功能。我嘗試了各種方法,但我無法成功超載h函數,並使所有使用註釋下列出的CallExpressions都可以通過。用於hyperscript簽名的TypeScript函數重載

這是我到目前爲止有:

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 

回答

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