javascript - 如何确保扩展类必须在 TypeScript 中设置属性值?

标签 javascript oop inheritance typescript

如果我有一个类foo:

class Foo {
  id: number
  name: string

  sayHi() {
    console.log('hi')
  }
}

如何确保从 foo 扩展的任何类都必须设置 idname 的值?

class Bar extends Foo {
  // must set these values
  id = 1
  name = 'bar'
}

这个概念或模式有名称吗?我不能将 Foo 作为接口(interface),因为它必须具有继承类可以使用的方法。

最佳答案

Foo需要它们作为参数的构造函数:

class Foo {
  constructor(public id: number, public name: string) {
    // Validate them here if desired
  }

  sayHi() {
    console.log('hi');
  }
}

由于子类必须调用其父类(super class)构造函数(隐式或显式),因此尝试在不传入必要参数的情况下执行此操作将被 TypeScript 编译器标记为:Supplied parameters do not match any signature of call target.例如,这两种方法都失败了:

class Bar extends Foo {
}
const b = new Bar();   // Supplied parameters do not match any signature of call target.

class Bar extends Foo {
  constructor() {
    super();           // Supplied parameters do not match any signature of call target.
  }
}

请注意此处使用的有趣的 TypeScript 功能:因为我们在构造函数参数上给出了访问修饰符,所以在调用构造函数时会自动创建实例属性并将其设置为这些值。它相当于:

class Foo {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
    // Validate them here if desired
  }

  sayHi() {
    console.log('hi');
  }
}

(因为默认修饰符是 public 。)

关于javascript - 如何确保扩展类必须在 TypeScript 中设置属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376854/

相关文章:

javascript - 为什么 node.js 运行时比 Google chrome 控制台慢

c++ - 没有公共(public)继承的类之间的链式转换

C++ 抽象基类构造函数/析构函数 - 一般正确性

css - CSS <li> 的填充和边距根本不起作用

C++继承。获取基类的数据成员值

javascript - jQuery 返回元素属性的初始值

javascript - 为什么我的脚本无法加载 jQuery Mobile?

javascript - 在 JWPlayer 5.9 中突出显示当前事件的播放列表项

javascript - 基于类和基于对象的语言比较(ECMAScript 规范)

c# - 什么是标记接口(interface)?