Home > Back-end >  TypeScript. Classes. Is it possible to avoid writing a constructor, when there are props?
TypeScript. Classes. Is it possible to avoid writing a constructor, when there are props?

Time:07-27

For example I have a class and an interface for props:

interface PropsInterface {
 propertyName: dataType
}
class Example {
  constructor(props: PropsInterface) {
     this.exampleProps = props
  }

  exampleProps: PropsInterface
}

Is it possible to avoid writing a constructor ?

For example something similar to React class components with props, where we can simply write so:

class Example extends React.Component<PropsInterface, any> {
  exampleProps = this.props.propertyName
}

Thank You!

CodePudding user response:

You can qualify constructor parameters with an access modifier (private, protected, public or readonly), and they will automatically get converted into class properties:

interface PropsInterface {
  propertyName: string;
}

class Example {
  constructor(public props: PropsInterface) {}
}

console.log(new Example({ propertyName: 'test' }).props);

The handbook refers to this as "parameter properties". See here for details.

CodePudding user response:

If you put a ! at the end of propertyName, typescript won't check if it's in the constructor.

 interface PropsInterface {
     propertyName!: dataType
 }
  • Related