Skip to content

Instantly share code, notes, and snippets.

@spion
Created December 6, 2016 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spion/4a1120aa15f97a786c8cc576838340fd to your computer and use it in GitHub Desktop.
Save spion/4a1120aa15f97a786c8cc576838340fd to your computer and use it in GitHub Desktop.
type Json = null | boolean | string | number | Array<{}> | {}
function tArray<T>(f:(t:any) => t is T) {
return function (a:any): a is Array<T> {
if (!Array.isArray(a)) return false;
for (var k = 0; k < a.length; ++k)
if (!f(a[k])) return false;
return true;
}
}
function tString(t: any): t is string { return typeof t === 'string' }
function tBoolean(t: any): t is boolean { return typeof t === 'boolean' }
function tObject<T>(checker: {[p in keyof T]: (t:any) => t is T[p]}) {
return function(obj: any): obj is {[p in keyof T]: T[p] } {
for (var key in checker) if (!checker[key](obj[key])) return false;
return true;
}
}
var isTodoList = tObject<{items: Array<{text: string, completed: boolean}>, showCompleted: boolean}>({
items: tArray(tObject<{text: string, completed: boolean}>({text: tString, completed: tBoolean})),
showCompleted: tBoolean
})
function test(j:Json) {
if (isTodoList(j)) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment