Skip to content

Instantly share code, notes, and snippets.

@literalplus
Last active October 15, 2019 21:05
Show Gist options
  • Save literalplus/b8249a936599fea0dd02ff1768de7a1a to your computer and use it in GitHub Desktop.
Save literalplus/b8249a936599fea0dd02ff1768de7a1a to your computer and use it in GitHub Desktop.
Example of getting enum values by a string key in TypeScript
interface AxiosResponse {
data?: any;
}
enum ErrorKey {
ServerError = 1,
WeirdException,
UnknownError,
}
type ErrorKeyString = keyof typeof ErrorKey;
function errorKeyFromString(response: AxiosResponse): ErrorKey | null {
if (!("data" in response && "errorKey" in response.data)) {
return null;
}
// this works because data has any type
const keyString: ErrorKeyString = response.data.errorKey;
return ErrorKey[keyString] || null;
}
function isErrorKeyString(maybeKey: string): maybeKey is ErrorKeyString {
return !!maybeKey && ErrorKey[maybeKey as ErrorKeyString] !== undefined;
}
function errorKeyFromString2(response: AxiosResponse): ErrorKey | null {
const hasErrorKey = "data" in response && "errorKey" in response.data;
if (!hasErrorKey) {
return null;
}
const keyString = response.data.errorKey;
// isErrorKeyString acts as a type predicate here, so we don't need to define the type
// ref: https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates
return isErrorKeyString(keyString) ? ErrorKey[keyString] : null;
}
function demo(keyString: string | undefined) {
const response: AxiosResponse = {
data: {
errorKey: keyString,
parameters: [],
}
}
// this is actually the enum ordinal at runtime
const keyOrdinal = errorKeyFromString(response);
const keyOrdinal2 = errorKeyFromString2(response);
keyOrdinal == keyOrdinal2 || console.error('impl mismatch!');
if (!keyOrdinal) {
console.log(" ->", keyString, "is an unknown error key.");
} else {
// note that we could just use keyString here as well,
// this is mainly for demonstrating how to get the key string
// from the enum object/ordinal
const keyName = ErrorKey[keyOrdinal];
console.log(" ->", keyString, "was mapped to ordinal", keyOrdinal, "which is", keyName);
}
}
demo("WeirdException");
demo("whatever");
demo(undefined);
// output:
// -> WeirdException was mapped to ordinal 2 which is WeirdException
// -> whatever is an unknown error key.
// -> undefined is an unknown error key.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment