Fyro
Fyro

Reputation: 65

Merge object keys into class

So, I have an external object whose properties get assigned to the class. How would I make typescript understand that those keys would become class' keys?

const object = {
  objectKey: 'whatever'
}

class someClass {
  classKey: string

  constructor(){
    Object.keys(object).forEach(key => this[key] = key)
  }

  someMethod(){
    console.log(this.objectKey) // how do I make it understand it exists?
  }
}

Upvotes: 0

Views: 323

Answers (1)

jcalz
jcalz

Reputation: 327964

In cases where you want the compiler to know that a class's instance interface has more properties, you can use declaration merging. Here's how I might do it:

type MyObject = typeof object; // make a named type with statically known keys
interface SomeClass extends MyObject { } // declare the SomeClass interface as extending it
class SomeClass { ... } // merge the SomeClass class instance interface into it

Then the compiler will see the keys/values of object as belonging to SomeClass instances too. Note that this circumvents the --strictPropertyInitialization protection and will not warn you if you fail to initialize the merged-in properties. So be careful to do it right. Maybe like this:

class SomeClass {
    classKey: string = "initializeMePlease" // compiler will catch if you don't do this

    constructor() {
        Object.assign(this, object); // compiler will not catch if you don't do this
    }

    someMethod() {
        console.log(this.objectKey); // no error here now
    }
}

Playground link

Upvotes: 1

Related Questions