【问题标题】:how to make an extension of string in typescript?如何在打字稿中扩展字符串?
【发布时间】:2021-06-18 17:46:22
【问题描述】:

我需要将我自己的方法添加到打字稿中的字符串中。所以希望我能做这样的事情

const myPoint : string = "23";
const customNumber = myPoint.convertUsingMyCustomImplementation();

我试试这个(使用大写的 S):

// eslint-disable-next-line no-extend-native
String.prototype.convertUsingMyCustomImplementation = function() : number {
  return parseFloat(this);
};

但我有两个错误

类型上不存在属性“convertUsingMyCustomImplementation” '字符串'。

“字符串”类型的参数不能分配给类型参数 '细绳'。 'string' 是一个原始的,但 'String' 是一个包装对象。 尽可能使用“字符串”。

我也试试下面的代码:

// eslint-disable-next-line no-extend-native
string.prototype.convertUsingMyCustomImplementation = function() : number {
  return parseFloat(this);
};

但我也有错误

如何使用 Typescript 来实现?

【问题讨论】:

标签: typescript


【解决方案1】:

您的原型方法很好。您只需声明该字符串将具有此方法。通常您在 .d.ts 文件中执行此操作以使其可以在任何地方工作,但您可以在紧要关头在常规 ts 文件中执行此操作。

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

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 2021-08-10
    • 2019-09-18
    • 2018-07-25
    • 2020-03-26
    • 1970-01-01
    • 2019-03-22
    • 2020-07-07
    相关资源
    最近更新 更多