I'm using TypeScript to develop my application. I'm trying to create an interface (or type) that is one of several constants, or a random string.
Pseudo code to describe what I'm trying to build:
contants.ts
:
export const ERROR_A = "Error A";
export const ERROR_B = "Error B";
export const ERROR_C = "Error C";
types.ts
:
type SWITCH_ERROR = ERROR_A | ERROR_B | ERROR_C | string
I know this way every string can be an error. The reason why I want to do it like this, is so that the codebase can be easily maintained and every known error has it's type. The error will later get handled in a switch statement like this:
switchExample.ts
:
export const someFunc(error: SwitchError): void => {
switch(error) {
case ERROR_A:
// Do something
// ... continue for each error.
default:
// Here the plain string should be handled.
}
}
The problem is I tried doing it like this:
import { ERROR_A } from "./some/Path";
export type SwitchError = ERROR_A;
But this throws the error:
[ts] Cannot find name 'ERROR_A'.
What am I doing wrong? How would one design something like this in TypeScript? Or is this bad design? If yes how else could I do this?
The error is because you have only defined ERROR_A
as a value but you are trying to use it as a type. (The error message is unhelpful; I recently filed an issue to improve it.) To define each name as both a value and a type, you could use the following in constants.ts
:
export const ERROR_A = "Error A";
export type ERROR_A = typeof ERROR_A;
export const ERROR_B = "Error B";
export type ERROR_B = typeof ERROR_B;
export const ERROR_C = "Error C";
export type ERROR_C = typeof ERROR_C;
Hayden Hall's suggestion to use an enum is also good, since enum members are automatically defined as both names and types. But you could avoid all of this and just write type SWITCH_ERROR = string
; it's equivalent to type SWITCH_ERROR = ERROR_A | ERROR_B | ERROR_C | string
when ERROR_A
, ERROR_B
, and ERROR_C
are specific strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With