【发布时间】: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 来实现?
【问题讨论】:
-
当您使用
String.prototype和String: this时发生了什么?你试过了吗? (我不使用打字稿)
标签: typescript