Created
March 7, 2018 17:55
-
-
Save styfle/290c5f5ce593592d6f7ada96e6f22bfd to your computer and use it in GitHub Desktop.
Answer to stackoverflow question 49156502
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
function isDate(obj: any): obj is Date { | |
return typeof obj === 'object' && 'toISOString' in obj; | |
} | |
function isString(obj: any): obj is string { | |
return typeof obj === 'string'; | |
} | |
interface JWT { | |
id: string; | |
auth_token: string; | |
expires_in: Date; | |
} | |
function isJwt(obj: any): obj is JWT { | |
const o = obj as JWT; | |
return o !== null | |
&& typeof o === 'object' | |
&& isString(o.id) | |
&& isString(o.auth_token) | |
&& isDate(o.expires_in); | |
} | |
function print(jwt: any) { | |
if (typeof jwt === 'string') { | |
try { | |
jwt = JSON.parse(jwt); | |
} catch (e) { | |
console.error(`String is not JSON: ${jwt}`); | |
} | |
} | |
if (isJwt(jwt)) { | |
console.log(`Found jwt: ${jwt.id} ${jwt.auth_token} ${jwt.expires_in}`); | |
} else { | |
console.error(`Object is not of type jwt: ${jwt}`); | |
} | |
} | |
print(42); | |
print('failing'); | |
print(null); | |
print(undefined); | |
print({}); | |
print({ id: 'id01', auth_token: 'token01', expires_in: new Date(2018, 11, 25) }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment