在扩展 class 中重新定义实例变量的类型

Re-define type of instance variable in an extended class

我有一个关于 inheritance and types for instance variables in typescript 的问题。

假设我有一个简单的 class 如下:

class Person {
  instanceVariable: Object;
  age: Number;

  constructor(instanceVariable: Object, age: Number) {
    this.instanceVariable = instanceVariable;
    this.age = age;
  } 
};

let alice = new Person({}, 50);  //This will work
let sarah = new Person({}, "fifty"); //Typescript will complain here..

Typescript 可以满足您的预期。当您尝试创建 sarah 时它会抱怨 :)。 但是现在让我们假设你有另一个扩展它的 class,你想确保这个 class 仍然 实例变量但是 覆盖类型。

//Create a simple class that extends and overrides the type
class Student extends Person {
  instanceVariable: String 
}

let bvk = new Student("test", 50);  //This should work
let katie = new Student(50, 50);  //This shouldn't work

不幸的是,这并没有真正按预期工作。打字稿抱怨:“属性 'instanceVariable' 没有初始化器,并且在构造函数中没有明确分配。”

如果您尝试添加构造函数,我对如何使其工作感到困惑,因为我基本上想调用“super”来设置数据。不过这也不管用,打字稿也有同样的抱怨!

class Student extends Person {
  instanceVariable: String;
  constructor(instanceVariable: String, age: Number){
    super(instanceVariable, age)
  }
}

无论如何,我可能想的都是错的,但我真的很好奇如何最好地考虑它。

您可以为您的 Person class 使用通用类型:

class Person<T = object> {
  instanceVariable: T;

  constructor(instanceVariable: T, age: number) {
    // ...
  } 
}

您的 Student 然后可以扩展 Person 如下:

class Student extends Person<string> {}

PS: 看看第一个点 Do's and Don'ts