Home > OS >  Is it possible to use static variables for type definitions?
Is it possible to use static variables for type definitions?

Time:11-09

I have some classes with a static variable indicating their type. I want to create a union type based on thoses static variables

class Foo {
  static typeId = 'i-am-foo';
}

class Bar {
  static typeId = 'i-am-bar';
}

type MyUnionType = Foo.typeId | Bar.typeId;

TS playground

Unfortunately this is not possible, I get the error

'Foo' only refers to a type, but is being used as a namespace here.

Is it possible to use static variables for type definitions?

CodePudding user response:

i-am-foo and i-am-bar are values, and not types and you are trying to access them and combine to create a union. To do that correctly, you will need to get the type of them using typeof.

Also, type your static values correctly using the right type. If you do not specify :

  static typeId :'i-am-foo'= 'i-am-foo';

the type of typeId would be the broad type string, and union of both string types will be string.

Note: One more way to do this would be:

  static typeId = 'i-am-foo' as const;

as const will tell TS to try and find the narrowest type.

Your code would look like:

class Foo {
  static typeId :'i-am-foo'= 'i-am-foo';
}

class Bar {
  static typeId : 'i-am-bar' = 'i-am-bar';
}

type MyUnionType = typeof Foo.typeId | typeof Bar.typeId;

Playground

  • Related