Skip to content Skip to sidebar Skip to footer

Use Const Values As Union Type Options Typescript

Consider this example: const FIRST = 'FIRST' const SECOND = 'SECOND' type TOptions = FIRST | SECOND const someFunction = (options: TOptions): void => { // do something, no

Solution 1:

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

constFIRST = 'FIRST'constSECOND = 'SECOND'type TOptions = typeofFIRST | typeofSECOND;

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

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

Playground Link

Solution 2:

You can declare those constants as types:

// It's a good idea to export these types // since you want them to be used external filesexporttypeFIRST = "FIRST"exporttypeSECOND = "SECOND"exporttype TOptions = FIRST | SECOND// and then a call to your function will besomeFunction("FIRST") // oksomeFunction("SECOND") // oksomeFunction("THIRD") // Argument of type '"THIRD"' is not assignable to parameter of type 'TOptions'.(2345)

Another option is to use an enum type:

exportenumOptions {
  FIRST = 'FIRST',
  SECOND = 'SECOND'
}

constotherFunction = (options: Options) => {}

otherFunction(Options.FIRST)
otherFunction(Options.SECOND)

Post a Comment for "Use Const Values As Union Type Options Typescript"