Skip to content

Instantly share code, notes, and snippets.

@KeithGillette
Created February 5, 2018 21:54
Show Gist options
  • Save KeithGillette/e20c2bc9201261d2a9627c060fee23bb to your computer and use it in GitHub Desktop.
Save KeithGillette/e20c2bc9201261d2a9627c060fee23bb to your computer and use it in GitHub Desktop.
TypeScript Type Guard: Duck Type Equivalent To Class
export interface IClassConstructor<T> {
new (...args: any[]): T;
}
/** generic TypeScript Type Guard
* https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
*/
export function isDuckTypeEquivalentToClass<T>(objectToTest: any, classToTest: IClassConstructor<T>): objectToTest is T {
if (objectToTest instanceof classToTest) {
return true;
} else {
const instance = new classToTest();
for (const key in instance) {
if (!(key in objectToTest)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment