【问题标题】:why doesn't this overloading function signature work?为什么这个重载函数签名不起作用?
【发布时间】: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


【解决方案1】:

由于 createElement 函数的输出类型取决于它的输入类型参数,我们应该使用泛型而不是具体类型,我们不应该使用重载语法。

无论如何我们应该以这种方式实现它:

function createElement<T extends keyof HTMLElementTagNameMap>
(tag: T, options?:ElementCreationOptions): HTMLElementTagNameMap[T] {
    return document.createElement(tag, options)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    相关资源
    最近更新 更多