【问题标题】:Typescript - How do I add an extension methodTypescript - 如何添加扩展方法
【发布时间】:2019-11-28 12:39:47
【问题描述】:

我读到你可以在 Typescript 中创建扩展方法,我查了一些代码

然后将该代码放在我的扩展 methods.ts 中,但我收到一条错误消息,指出 toNumber 不存在。我怎样才能解决这个问题?

【问题讨论】:

  • String 定义了严格的接口。如果您想使用其他方法,则需要定义自己的字符串,例如type MyString = String & {toNumber: () => number}。
  • @MaciejSikora 见下面的例子????

标签: typescript extension-methods


【解决方案1】:

你可以通过augmenting global scope扩展String接口:

export { };

declare global {
    interface String {
        toNumber(): number;
    }
}

String.prototype.toNumber = function (this: string) { return parseFloat(this) };

Playground

【讨论】:

  • 什么是 export { };做什么?
  • @MikeOttink 您只能在模块中增加全局范围。如果文件具有导入或导出,则将其视为模块。因此,将其设为“模块”是一种解决方法。如果文件有其他导入或导出,则不需要
【解决方案2】:

您可以像这样扩展String 接口:

interface String {
    toNumber(): number;
}

String.prototype.toNumber = function(this: string) {
    return parseFloat(this);
}

const s = '123.45';
s.toNumber();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2012-07-12
    相关资源
    最近更新 更多