Skip to content

Instantly share code, notes, and snippets.

@calexandrepcjr
Created February 24, 2020 10:31
Show Gist options
  • Save calexandrepcjr/23470847e833eb317bfa6561ca867309 to your computer and use it in GitHub Desktop.
Save calexandrepcjr/23470847e833eb317bfa6561ca867309 to your computer and use it in GitHub Desktop.
A way to load string enum values from request to your domains without doing nasty unsafe casts or turning off type assertion
/*
A way to load string enum values from request to your domain
without doing nasty unsafe casts or turning off type assertion
Usage:
public deserialize(input: string): Entity {
const serializedEntity = JSON.parse(input) as SerializedEntity;
return new |Entity(
new StringEnumValue(serializedEntity.type, EntityType).toString(),
serializedEntity.entityId,
new StringEnumValue(serializedEntity.status, EntityStatus).toString(),
new Date(serializedEntity.statusUpdatedAt),
new Date(serializedEntity.activatedAt),
);
}
*/
type ValueOf<T> = T[keyof T];
type KeyOf<T> = keyof T;class StringEnumValue<E> {
public constructor(private readonly value: string, private readonly enumerable: E) {}
public toString(): ValueOf<E> {
const key = this.value.toUpperCase(); if (!Object.keys(this.enumerable).includes(key)) {
throw new Error(`Key not found: ${key}`);
} return this.enumerable[key as KeyOf<E>];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment