You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中创建类似Array的带实例方法的自定义类型?

在TypeScript中实现带自身访问方法的自定义类型

要实现类似Array那样,方法能直接访问自身值的自定义类型,核心是利用this关键字引用当前实例的状态,以下是几种可行方案:

1. 使用类(推荐方案)

类是最直观且符合TypeScript面向对象设计的方式,实例方法可通过this直接访问当前实例的值,无需额外传参:

class MyNumber {
  private value: number;

  constructor(initialValue: number) {
    this.value = initialValue;
  }

  add(num: number): number {
    this.value += num;
    return this.value;
  }

  getValue(): number {
    return this.value;
  }
}

// 使用示例
const myVar = new MyNumber(5);
console.log(myVar.add(2)); // 输出7
console.log(myVar.getValue()); // 输出7

如果希望实例能像原始数值一样参与运算,可以添加valueOf方法实现隐式类型转换:

class MyNumber {
  private value: number;

  constructor(initialValue: number) {
    this.value = initialValue;
  }

  add(num: number): number {
    this.value += num;
    return this.value;
  }

  valueOf(): number {
    return this.value;
  }
}

const myVar = new MyNumber(5);
console.log(myVar + 3); // 输出8(隐式调用valueOf)
console.log(myVar.add(2)); // 输出7

2. 扩展原始类型原型(不推荐)

若想让原始数值直接拥有自定义方法,可扩展Number原型,但这种方式会污染全局原型,易引发兼容性问题,不建议生产环境使用:

// 声明类型,避免TypeScript报错
interface Number {
  add(num: number): number;
}

// 实现方法
Number.prototype.add = function(num: number): number {
  return this + num;
};

// 使用示例
const myVar: number = 5;
console.log(myVar.add(2)); // 输出7

3. 类型别名+工厂函数(适合简单场景)

如果不想定义类,可通过类型别名结合工厂函数封装值与方法,适合临时或简单场景:

type MyCustomType = {
  value: number;
  add: (num: number) => number;
};

function createMyCustomType(initialValue: number): MyCustomType {
  return {
    value: initialValue,
    add(num: number) {
      this.value += num;
      return this.value;
    }
  };
}

// 使用示例
const myVar = createMyCustomType(5);
console.log(myVar.add(2)); // 输出7
console.log(myVar.value); // 输出7

内容的提问来源于stack exchange,提问作者Mateus Dreher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:57:25