Created
February 24, 2020 10:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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