Typescript:在类中扩展“ this”

问题描述 投票:0回答:1

我有一个类Foo,我想用我拥有的一些文字对象动态地扩展它。如何在没有在单独的界面中手动重复文字对象的键的情况下保持this的键入?

const someLiteralObject = {
  key1: 'foo',
  key2: 'bar',
  //  ...lots of more keys
}

class Foo {
   constructor(){
      Object.assign(this, someLiteralObject)
   }
   test() {
    console.log(this.key1); //error: Property 'key1' does not exist on type 'Foo'
   }
}

const test = new Foo();
console.log(test.key1); //error: Property 'key1' does not exist on type 'Foo'
typescript class this extends
1个回答
0
投票

强类型方式:

class Some {
        key1: string;
        key2: string;
}

const someLiteralObject: Some = {
  key1: 'foo',
  key2: 'bar',
}

class Foo extends Some {
   constructor(){
      super();
      Object.assign(this, someLiteralObject)
   }
   test() {
    console.log(this.key1);
   }
}

const test = new Foo();
console.log(test.key1);

笨拙的方式(例如,当您不知道对象将拥有哪些键时)

const someLiteralObject = {
  key1: 'foo',
  key2: 'bar',
}

class Foo {
   constructor(){
      Object.assign(this, someLiteralObject)
   }
   test() {
    console.log((this as any).key1);
   }
}

const test = new Foo();
console.log((test as any).key1);
© www.soinside.com 2019 - 2024. All rights reserved.