Last active
July 15, 2016 22:16
-
-
Save hunan-rostomyan/bbc5440aaf42efe8896e64adac168143 to your computer and use it in GitHub Desktop.
Type Assertion
This file contains 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
// Problem | |
function handler(event: Event) { | |
let element = event as HTMLElement; // Error : Neither 'Event' not type 'HTMLElement' is assignable to the other | |
} | |
// Approach 1 (using any) | |
function handler(event: Event) { | |
let element = event as any as HTMLElement; // Basarat calls this "double assertion" | |
} | |
// Approach 2 (using union types) | |
function handler(eventOrElement: Event | HTMLElement) { | |
let element = eventOrElement as HTMLElement; | |
} | |
// Source: https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment