Jan Peter
Jan Peter

Reputation: 920

Using generic types in constructor call without using types in the parameters

Is it possible to use generics in a constructor call without using the types in the parameters like that, or is there another way of doing this?

type PersonProps = {
  name: string,
}

class Model<P> {
  label: string;

  constructor(label: string) {
    this.label = label;
  }

  create(props: P): Promise<any> { ... }
}

const Person = new Model<PersonProps>('Person');

EDIT:

I get the following flow errors in Visual Studio Code and no autocomplete results at all:

test.js:11
11: const Person = new Model<PersonProps>('Person');
                    ^^^^^^^^^^^^^^^^^^^^^ boolean. This type cannot be compared to
11: const Person = new Model<PersonProps>('Person');
                                          ^^^^^^^^ string

test.js:11
11: const Person = new Model<PersonProps>('Person');
                              ^^^^^^^^^^^ PersonProps. type referenced from value position
  5: type PersonProps = {
          ^^^^^^^^^^^ type PersonProps

Upvotes: 1

Views: 99

Answers (1)

Nat Mote
Nat Mote

Reputation: 4086

You don't need to (and in fact cannot) specify the type parameter there:

const Person = new Model('Person');

If you would like to specify the full type, with the type parameter, for the Person variable, you can add a type annotation:

const Person: Model<PersonProps> = new Model('Person');

The errors you are seeing are due to the fact that the < and > characters parse as "less than" and "greater than" in that context.

Upvotes: 1

Related Questions