Skip to content

Instantly share code, notes, and snippets.

@spion
Created October 30, 2017 21:41
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/38d701bf1dda4c000b0b270fa82a1cca to your computer and use it in GitHub Desktop.
Save spion/38d701bf1dda4c000b0b270fa82a1cca to your computer and use it in GitHub Desktop.
type Checker<T> = (x: any) => x is T;
function tArray<T>(f: Checker<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]: Checker<T[P]> }) {
return function(obj: any): obj is T {
for (var key in checker) if (!checker[key](obj[key])) return false;
return true;
}
}
var isTodoList = tObject({
items: tArray(tObject({
text: tString,
completed: tBoolean
})),
showCompleted: tBoolean
});
function test(x: any) {
if (isTodoList(x)) {
x; // { items: { text: string, completed: boolean }[], showCompleted: boolean }
}
}
:tada: 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment