Heisenberg
Heisenberg

Reputation: 5299

How to read typescript constructor and Record<> sentence

When I read following code, I stacked the following constructor

https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts

I'd like to understand what the

① What is string | Record<string, any>, ? what is the mean of this ?

② What is super(); in this context ?

③Basically why this constructor is needed?

  constructor(
    private readonly response: string | Record<string, any>,
    private readonly status: number,
  ) {
    super();
    this.initMessage();
  }

If someone has opinion, please let me know. Thanks

Upvotes: 1

Views: 1339

Answers (3)

Teneff
Teneff

Reputation: 32158

Record<Keys, Type> is an utility type (built-in type)

Constructs a type with a set of properties Keys of type Type. This utility can be used to map the properties of a type to another type.

Example

// an object where the keys are 'first' and 'second' and the value is a number
const test: Record<'first' | 'second', number> = {
  'first': 123,
  'second': 456
}

In your case Record<string, any> it would be an object with any string as a key and any value.

super is the class that the current class extends' constructor and with super.method() you can call super class' methods

③ Why is it needed - It defines the two private properties, which could also be defined outside of the constructor. And why does it calls initMessage - that depends on the implementation

Upvotes: 4

Joshue
Joshue

Reputation: 346

1.- It means that the variable can be of 2 types: string or Record<string, any>

2.- The super keyword can be used in expressions to reference base class properties and the base class constructor. Super calls consist of the keyword super followed by an argument list enclosed in parentheses. Super calls are only permitted in constructors of derived classes.

3.- from what can be seen in the code, the constructor is used to initialize the variables or necessary methods from the moment the class is built

Upvotes: 0

joshvito
joshvito

Reputation: 1563

  1. string | Record<string, any> is a type definition for the response variable; it means the type will be string or Record<string, any>; you can read more about union typed at https://www.typescriptlang.org/docs/handbook/advanced-types.html

  2. in a constructor, you call super() when the class is extending another class. It looks like you omitted this part in your code snippet.

  3. constructor is needed to initialize the class in question with response and status and whatever the extended class inits too

Upvotes: 0

Related Questions