根据构造函数参数及其初始值将类型赋予父类的成员

时间:2019-02-23 22:15:09

标签: typescript types

我有一个父类说动物。

var options = {x: 10}
console.log(options.x + ' original options object');

cat(options);
function cat(options) {
  newOptions = Object.create(options);
  newOptions.x = 3;
  x = newOptions.x;
  console.log(x + ' cat = 3'); // this should equal 3
  mouse(x);
}

dog(options);

function dog(options) {
  newOptions = Object.create(options);
  newOptions.x = 7;
  x = newOptions.x;
  console.log(x + ' dog = 7'); // this should equal 7
  mouse(x);
}

// SHARED FUNCTION
function mouse(x) {
  console.log(x + ' mouse = cat() and/or dog()'); // I want this to equal 3 for cat() and 7 for dog() just as it is with x defined inside cat() and dog().
}

console.log(options.x + ' final global scope check = 10'); // I want this to remain 10, not 3. But the changes in cat() are poluting the global definition of options.x.

我的孩子上课的地方

class Animal {
  constructor(customProperties){
    this.properties = { legs: 4, wings: false, ...customProperties }
  }
  public properties // How to give type here as same as the value defined in the constructor and customProperties came in the customProperties.
}

现在如何在父类中赋予class Kangaroo extends Animals { super({legs: 2, mamal: true}); } 的类型与其值相同? UNION properties进入了构造函数。

1 个答案:

答案 0 :(得分:1)

首先,让我们将类型添加到Mammal类中。

interface AnimalProperties {
  legs: number;
  wings: boolean;
}

class Animal<T> {
  constructor(customProperties: T) {
    this.properties = { legs: 4, wings: false, ...customProperties };
  }

  public properties: AnimalProperties & T;
}

通过使用泛型类,我们可以允许动物拥有我们事先不知道的属性。示例:

const { legs, wings, predator } = new Animal({ predator: false }).properties;

现在我们可以进入专门的Kangaroo类。它代表Animal和一些其他属性的混合。我们称它们为KangarooProperties

注意:应该可以覆盖AnimalProperties,但不是强制性的。这就是为什么我扩展Partial<AnimalProperties>

interface KangarooProperties extends Partial<AnimalProperties> {
  mammal: true;
}

class Kangaroo<T> extends Animal<KangarooProperties & T> {
  constructor(customProperties: T) {
    super({ legs: 2, mammal: true, ...customProperties })
  }
}

我们最后的properties被正确识别。

const { cute, legs, mammal, wings } = new Kangaroo({ cute: true }).properties;

如果您的Kangaroo本身不应该采取任何选择,则可以跳过通用部分。

interface KangarooProperties extends Partial<AnimalProperties> {
  mammal: true;
}

class Kangaroo extends Animal<KangarooProperties> {
  constructor() {
    super({ legs: 2, mammal: true })
  }
}

请参见TypeScript Playground