Skip to content

Instantly share code, notes, and snippets.

@lil5
Last active September 15, 2020 11:21
Show Gist options
  • Save lil5/293549233ad983772b0c2f1333f809dc to your computer and use it in GitHub Desktop.
Save lil5/293549233ad983772b0c2f1333f809dc to your computer and use it in GitHub Desktop.
Typescript Utils
export function getObj<V>(getObj: () => V): V | undefined {
let value: undefined | V;
let shouldReturnUndefined: boolean = false;
try {
value = getObj();
} catch (e) {
if (e instanceof TypeError) {
shouldReturnUndefined = true;
}
}
if (shouldReturnUndefined) {
return undefined;
}
return value;
}
export function getOrReturn<T>(value: T | undefined | null, failover: T): T {
let result: T = failover;
if (value !== undefined && value !== null) {
result = value;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment