0

Consider this example:

const FIRST = "FIRST"
const SECOND = "SECOND"

type TOptions = FIRST | SECOND

const someFunction = (options: TOptions): void => {
    // do something, no return
}

I like to use const values in type declaration

type TOptions = FIRST | SECOND // not working

to restrict the range of selection. These const are used across the entire project, so it will be unwise to not to use them and type it like this:

type TOptions = "FIRST" | "SECOND" // working, as expected

I don't want to repeat myself and like to use const values as type union options.

How do I do that?

Andrew
  • 695
  • 1
  • 8
  • 21

2 Answers2

3

I believe you need to use typeof to make it work:

const FIRST = 'FIRST'
const SECOND = 'SECOND'

type TOptions = typeof FIRST | typeof SECOND;

const someFunction = (options: TOptions): void => {
// do something, no return
}

someFunction(FIRST); // works
someFunction('test'); // error

Playground Link

Wolph
  • 78,177
  • 11
  • 137
  • 148
  • 1
    [this link](https://stackoverflow.com/a/51529486/11069163) helps me clarify your answer and usage of `typeof` operator in Typescript. – Andrew Jul 06 '20 at 10:51
1

You can declare those constants as types:

// It's a good idea to export these types 
// since you want them to be used external files
export type FIRST = "FIRST"
export type SECOND = "SECOND"

export type TOptions = FIRST | SECOND

// and then a call to your function will be
someFunction("FIRST") // ok
someFunction("SECOND") // ok
someFunction("THIRD") // Argument of type '"THIRD"' is not assignable to parameter of type 'TOptions'.(2345)

Another option is to use an enum type:

export enum Options {
  FIRST = 'FIRST',
  SECOND = 'SECOND'
}

const otherFunction = (options: Options) => {}

otherFunction(Options.FIRST)
otherFunction(Options.SECOND)
Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43