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:
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
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 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)
Post a Comment for "Use Const Values As Union Type Options Typescript"