2

Given the following class:

class MyOb {
  foo: string; 

  setFields(props) {
    Object.assign(this, props);
  }
}

Is it possible to constrain the props parameter of setFields to the properties of MyObj? So that:

new MyOb().setFields({ foo: 'bar' })  // compiles
new MyOb().setFields({ x: 'bar' })    // fails, property x is not a part of MyOb

1 Answer 1

3

You're looking for keyof and mapped types:

setFields(props: { [TKey in keyof MyOb]?: MyOb[TKey] } ) {

Note the ?, since you want each property to be optional.

Demo

Docs

Sign up to request clarification or add additional context in comments.

1 Comment

I'd note that this will only allow you to set the public properties and methods of the class, but not private or protected ones. That's fine (even preferable) in most cases but it's something to be aware of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.