SHARE
TWEET

Untitled

a guest Aug 20th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. type AsJSON<T> =
  2.     T extends Date ? string :
  3.     T extends Function ? undefined :
  4.     T extends Symbol ? undefined :
  5.     T extends Array<any> ? AsJSONArray<T> :
  6.     T extends object ? AsJSONObj<T> :
  7.     T;
  8.  
  9. type AsJSONObj<T extends object> = {
  10.     [K in keyof T]: AsJSON<T[K]>
  11. };
  12.  
  13. type Inspect<T extends Array<any>> = T extends Array<infer X> ? X : never;
  14. interface AsJSONArray<T extends Array<any>> extends Array<AsJSON<Inspect<T>>> {}
  15.  
  16. type InvalidKeys<T> = {[K in keyof T]: AsJSON<T[K]> extends undefined ? K : never}[keyof T];
  17.  
  18. type JSONable<T> = InvalidKeys<T> extends never ? T : ObjectContainsInvalidKeys<InvalidKeys<T>>;
  19. type ObjectContainsInvalidKeys<T> = {_:void}
  20.  
  21. type User = {
  22.     age: number,
  23.     name: string,
  24.     hi: ()=> void,
  25.     createdAt: Date,
  26.     friends: User[]
  27. }
  28.  
  29. function userFromJSON(v: AsJSON<User>): User {
  30.     return {
  31.         age: v.age,
  32.         name: v.name,
  33.         createdAt: new Date(v.createdAt),
  34.         hi: ()=>{},
  35.         friends: v.friends.map(userFromJSON)
  36.     }
  37. }
  38.  
  39. function safeToJSON<T>(v: JSONable<T>): string {
  40.     return JSON.stringify(v);
  41. }
  42.  
  43. safeToJSON({hi: 1});
  44. safeToJSON({good: 'string'});
  45. safeToJSON({foo: ()=>{}, bar: 1});
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top