I am using React and Typescript and I have the following type:
export type TestEnum = "TEST1" | "TEST2";
I want to check if a variable is equal to one of these values. How can I access the TEST1 value, for example?
CodePudding user response:
I think you might be confusing types
with variables
, TypeScript doesn't exist in runtime and as such, you can't do comparisons between those types.
But you can still do some work around, and create those types from actual variables, like so:
// the "as const" will create a tuple with literal types , instead of [string, string]
const testEnums = ["TEST1", "TEST2"] as const;
type TestEnums = typeof testEnums[number] // "TEST1" | "TEST2"
This way, you can have your type and still use testEnums
const to check for equality.