【发布时间】:2023-01-21 16:25:01
【问题描述】:
当我尝试使用完整类型签名声明重载函数类型时,typescript 抛出错误。
例如:
// functions full type signature
type CreateElement = {
(tag : 'a') : HTMLAnchorElement,
(tag : 'canvas') : HTMLCanvasElement,
(tag : 'table') : HTMLTableElement,
(tag:string) : HTMLElement
}
// functions implementation
let createElement:CreateElement = (tag:string):HTMLElement => {
return document.createElement(tag)
}
/* error :
Type '(tag: string) => HTMLElement' is not assignable to type 'CreateElement'.
Type 'HTMLElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 21 more
*/
但它有效:
function createElement(tag:'a'):HTMLAnchorElement
function createElement(tag:'canvas'):HTMLCanvasElement
function createElement(tag:'table'):HTMLTableElement
function createElement(tag:string):HTMLElement
function createElement(tag:string) {
return document.createElement(tag)
}
【问题讨论】:
-
因为您尝试分配给变量的函数没有这些重载?
-
函数语句支持对函数表达式不支持的重载进行松散检查。正如 microsoft/TypeScript#47769 中所要求的,您可以认为它是函数表达式缺少的功能。这是否完全解决了您的问题?如果是这样,我会写一个答案来解释;如果没有,我错过了什么?
标签: typescript