Created
          February 5, 2018 21:54 
        
      - 
      
- 
        Save KeithGillette/e20c2bc9201261d2a9627c060fee23bb to your computer and use it in GitHub Desktop. 
    TypeScript Type Guard: Duck Type Equivalent To Class
  
        
  
    
      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
    
  
  
    
  | 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