What's the TypeScript "as" Keyword Used For?

Introduced in TypeScript 1.6, the as keyword in TypeScript is:

  • Used to cast a value to a more specific or less specific version of the expected type;
  • Commonly used when you have information about the specific type for the value that TypeScript may not be able to determine on its own;
  • Equivalent to the angle-bracket syntax (but casting/asserting type with "as" is the recommended way).

For example, you can use the as keyword when selecting DOM elements, where TypeScript knows that the return type is some kind of HTMLElement, but does not know the specific type (like in the following example where you might be expecting the narrower type; HTMLInputElement):

const checkbox = document.getElementById('myCheckbox') as HTMLInputElement;

// equivalent to the angle-bracket syntax:
// const checkbox = <HTMLInputElement>document.getElementById('myCheckbox');

If you were to specify a type which is not a subset or superset of the expected type, then TypeScript would result in an error:

// Error: Conversion of type 'HTMLElement | null' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
const checkbox = document.getElementById('myCheckbox') as string;

Please note that the "as" keyword does not perform any type assertions at runtime (as it's removed at compile-time). Therefore, this won't throw an exception or return null if the type assertion fails at runtime.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.