0

I've created a scale down version of my problem.

The class must initialize the default value of its "status" property. It's of type T which extends the string litteral type "PossibleStatus" made of 3 possible strings.

Typescript doesn't accept this. Can you help me figure out why?

A stackblitz to see it live

export type PossibleStatuses = 'idle' | 'on' | 'off';

export class StatefulNode<T extends PossibleStatuses> {

  private status: T = 'idle';

  constructor() { }

}
Jem
  • 6,226
  • 14
  • 56
  • 74
  • 1
    did you check https://stackoverflow.com/questions/17382143/create-a-new-object-from-type-parameter-in-generic-class – Hany Habib Apr 01 '20 at 20:17
  • hi @HanyHabib, thanks, but it seems related to the "T extends " using a string litteral. I've updated my question to better reflect this issue. – Jem Apr 01 '20 at 20:23
  • 1
    hello Jem to work , i think you need to do it as private status: PossibleStatuses = 'idle'; because the compiled JavaScript has all the type information erased, you can't use T to new up an object. – Hany Habib Apr 01 '20 at 20:29
  • Thanks @HanyHabib; it seems my use of the "extends" keyword is wrong. I expect it to mean "at least the 3 strings specified above" and that seems to be my problem. I'm now looking for the right way to code that. – Jem Apr 01 '20 at 20:53

1 Answers1

1

The following code demonstrates why you cannot initiate the status (type X = 'on' extends PossibleStatuses but doesn't include 'idle'):

export type PossibleStatuses = 'idle' | 'on' | 'off';

export class StatefulNode<T extends PossibleStatuses> {
  // Error
  private status: T = 'idle';
}

// Because
const unsafe = new StatefulNode<'on'>();
basarat
  • 261,912
  • 58
  • 460
  • 511
  • Thanks; I understeand now that "extends" doesn't mean "at least these 3 strings". Is there a way to say so? Because I have a "SpecializedStatefulNode" that has 5 possible statuses, including the 3 base statuses. – Jem Apr 01 '20 at 20:52
  • Ok, I understand - "extends" in the case of a string litteral type means "these, or a subset of these". The wider type would otherwise be "string". Is this understanding correct? – Jem Apr 01 '20 at 21:01