Skip to main content

Type AssertionTS Syntax to override TSC's Type Inference for Static Type of specific Value

aka Assert

const inputEl = <HTMLInputElement\>document.getElementById("form-input")
const inputEl = document.getElementById("form-input") as HTMLInputElement
if (inputEl) {
(inputEl as HTMLInputElement).value = "wasd"
}

Type Assertion removes Static Type safety, should avoid & use as last resort

Type AssertionType Cast in other Programming Language

Type Cast

aka type conversion of one type to another, in C/C++ - equiv to (implicit) type coersion or (explicit) reassignment in JS

Non-Null Assertion Operator

postfix ! Type Assertion to Assert that Variableundefined || null

Source: Exclamation Mark In TypeScript | Become Front-End Expert

Type Assertion equivalent to Type Cast in other Programming Language, however, does not throw Exception or work at Runtime

as

Type Assertion Type Operator to Assert Variable as Type

References

  1. asType Assertion Type Operator to Assert Variable as Type

  2. Non-Null Assertion Operator ↔ postfix ! Type Assertion to Assert that Variableundefined || null