Home > Software design >  Reference constants in type definition
Reference constants in type definition

Time:07-12

Typescript weirdness:

export type MyType = 0 | 1 | 2;

This works. But this does not:

export const ONE = 1;
export const TWO = 2;
export const THREE = 3;
export type MyType = ONE | TWO | THREE;

CodePudding user response:

With the second example you are in typespace using a value (the declared consts) to declare a type. you need to use typeof ONE TWO or THREE. In the first example, 1 2 and 3 count as types themselves.

CodePudding user response:

The problem is that you are defining MyType as a type and there you're referencing a variable. So what you need to actually do to match types with types is to request the type of your value. You can do that by using the typeof operator like:

export const ONE = 1;
export const TWO = 2;
export const THREE = 3;
export type MyType = typeof ONE | typeof TWO | typeof THREE;

Playground

CodePudding user response:

First of all you should use typeof, like mentioned in previous answer.

Second, if I understand correctly, you want to create type containing excatly these 3 given values. To do this, you need to use as const keywords.

For example:

export const A = 1 as const;
export const B = 2 as const;
export type MyType = typeof A | typeof B;

and more usefull example for const variable:

export const status = {
  FIRST: 1,
  SECOND: 2
} as const;

export type StatusType = typeof status[keyof typeof status];

export interface IEntity {
  id: number;
  status: StatusType;
}

// You can use it elsewhere like this:
const A: IEntity = {
  id: 1,
  type: status.FIRST
};
  • Related