Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Last active July 15, 2016 22:16
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 hunan-rostomyan/bbc5440aaf42efe8896e64adac168143 to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/bbc5440aaf42efe8896e64adac168143 to your computer and use it in GitHub Desktop.
Type Assertion
// 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