Introduced in TypeScript 1.6, the as
keyword is used for type assertions, which are a way to tell the TypeScript compiler that you, as a developer, have more information about the type of a value than the compiler can infer.
There are two forms of type assertions in TypeScript:
-
Angle-Bracket Syntax:
let someValue: any = 'this is a string'; let strLength: number = (<string>someValue).length;
-
as
Keyword:let someValue: any = 'this is a string'; let strLength: number = (someValue as string).length;
Both forms are equivalent, however, casting/asserting type with "as
" is the recommended way. It is also more jsx
/tsx
-friendly as it avoids potential conflicts with JSX syntax when compared to the angle-bracket syntax. That being said, you can use either syntax to cast a value to a more specific or less specific version of the expected type.
Consider a more practical example, where when selecting a DOM node, TypeScript knows that the return type is some kind of HTMLElement
, but does not know the specific type:
const checkbox = document.getElementById('myCheckbox') as HTMLInputElement; // equivalent to the angle-bracket syntax: // const checkbox = <HTMLInputElement>document.getElementById('myCheckbox');
In this example, the assertion suggests a narrower type (i.e. HTMLInputElement
) than what TypeScript might have been able to infer.
If you were to specify a type which is not a subset or superset of the expected type, then TypeScript will show the following 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;
It's important to note that type assertions do not perform any runtime checking (as the assertions are removed at compile-time). Therefore, this won't throw an exception if the type assertion fails at runtime.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.