Skip to content

Instantly share code, notes, and snippets.

@korniychuk
Created July 10, 2017 14:26
Show Gist options
  • Save korniychuk/0473f07c9d26b2aa1e455582153d2a17 to your computer and use it in GitHub Desktop.
Save korniychuk/0473f07c9d26b2aa1e455582153d2a17 to your computer and use it in GitHub Desktop.
types converter
/**
* This is helper class for parse server response
*/
export class To {
public static number(raw: any): number {
const n = Number(raw);
return raw === undefined || raw === null || isNaN(n) ? null : n;
}
public static boolean(raw: any): boolean {
return raw === undefined || raw === null ? null : Boolean(Number(raw));
}
public static string(raw: any): string {
return raw === undefined || raw === null ? null : String(raw);
}
public static object(raw: any): object {
return raw === undefined || raw === null || raw instanceof Object === false ? null : raw;
}
public static array<T extends any>(raw: any): Array<T> {
return raw === undefined || raw === null || raw instanceof Array === false ? null : raw;
}
public static empty<T, R>(raw: R, cb: {(raw: R): T}): T | R {
return raw === undefined || raw === null ? null : (cb instanceof Function ? cb(raw) : raw);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment