如何在 Typescript 中扩展 String Prototype 并在接下来使用它? [英] How to extend String Prototype and use it next, in Typescript?

查看:34
本文介绍了如何在 Typescript 中扩展 String Prototype 并在接下来使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一种新方法扩展 String 原型链,但是当我尝试使用它时,它向我抛出一个错误:property 'padZero' 在类型 'string' 上不存在.谁能帮我解决这个问题?

I am extending String prototype chain with a new method but when I try to use it it throws me an error: property 'padZero' does not exist on type 'string'. Could anyone solve this for me?

代码如下.你也可以在 Typescript Playground 中看到同样的错误.

The code is below. You can also see the same error in Typescript Playground.

interface NumberConstructor {
    padZero(length: number);
}
interface StringConstructor {
    padZero(length: number): string;
}
String.padZero = (length: number) => {
    var s = this;
    while (s.length < length) {
      s = '0' + s;
    }
    return s;
};
Number.padZero = function (length) {
    return String(this).padZero(length);
}

推荐答案

如果您想扩充 class 而不是 instance,请扩充构造函数:

If you want to augment the class, and not the instance, augment the constructor:

declare global {
  interface StringConstructor {
    padZero(s: string, length: number): string;
  }
}

String.padZero = (s: string, length: number) => {
  while (s.length < length) {
    s = '0' + s;
  }
  return s;
};

console.log(String.padZero('hi', 5))

export {}

*如果您在 .tsdeclare global 并且不导出任何内容,则需要底部的空导出.这会强制文件成为模块.*

*The empty export on the bottom is required if you declare global in .ts and do not export anything. This forces the file to be a module. *

如果你想要instance(又名prototype)上的函数,

If you want the function on the instance (aka prototype),

declare global {
  interface String {
    padZero(length: number): string;
  }
}

String.prototype.padZero = function (length: number) {
  let d = String(this)
  while (d.length < length) {
    d = '0' + d;
  }
  return d;
};

console.log('hi'.padZero(5))

export {}

这篇关于如何在 Typescript 中扩展 String Prototype 并在接下来使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆