How to Use Type Assertions in TypeScript
What you’ll build or solve
You’ll apply type assertions to values like unknown, union types, and DOM elements. After finishing, you can narrow types intentionally and avoid unnecessary compiler errors while keeping your code readable.
When this approach works best
Type assertions work best when you:
Learn TypeScript on Mimo
- Access DOM elements with a known, specific type
- Narrow a union type after performing a runtime check
- Work with unknown values such as parsed JSON
- Integrate with third-party libraries that return broad types
For example, you may know that a queried element is an HTMLInputElement, or that a value inside a guarded block is an Admin. Type assertions help you express that knowledge to the compiler.
This is a bad idea if you use assertions to silence real type errors. Assertions do not validate anything at runtime.
Prerequisites
- TypeScript installed
- A
.tsfile - Basic understanding of interfaces, unions, and type guards
Step-by-step instructions
Step 1: Use a type assertion to override inference
The standard syntax uses the as keyword.
constvalue:unknown="Hello";
constlength= (valueasstring).length;
You are telling TypeScript to treat value as a string.
A common real-world example is working with DOM elements:
constinput=document.querySelector("#username")asHTMLInputElement;
input.value="Alex";
Without the assertion, TypeScript sees Element | null. After asserting HTMLInputElement, you can access .value.
You can also assert after narrowing a union type:
typeUser= { name:string };
typeAdmin= { name:string; role:string };
functionprintRole(person:User|Admin) {
if ("role"inperson) {
constadmin=personasAdmin;
console.log(admin.role);
}
}
The runtime check ensures the property exists before asserting.
TypeScript also supports angle bracket syntax:
constlength= (<string>value).length;
Avoid this form in .tsx files because it conflicts with JSX. Prefer as in modern projects.
What to look for:
- Assertions do not change runtime behavior
- The compiler trusts you completely
- Incorrect assertions cause runtime errors
getElementByIdandquerySelectormay returnnull- Angle bracket syntax does not work in JSX
Examples you can copy
Example 1: Assert a parsed JSON object
interfaceProduct {
id:number;
name:string;
}
constdata=JSON.parse('{"id":1,"name":"Laptop"}')asProduct;
console.log(data.name);
TypeScript now treats data as a Product.
Example 2: Narrow an unknown value safely
functionprintLength(value:unknown) {
if (typeofvalue==="string") {
conststr=valueasstring;
console.log(str.length);
}
}
The runtime check protects you before asserting.
Example 3: Work with form elements
constform=document.getElementById("loginForm")asHTMLFormElement|null;
if (form) {
form.reset();
}
You account for the possible null result.
Common mistakes and how to fix them
Mistake 1: Asserting the wrong type
What you might do:
constvalue:unknown=42;
constlength= (valueasstring).length;
Why it breaks:
At runtime, 42 is not a string. Accessing .length throws an error.
Correct approach:
if (typeofvalue==="string") {
console.log(value.length);
}
Check the type before asserting.
Mistake 2: Using as any to silence errors
What you might do:
constresult=someFunction()asany;
result.nonExistentProperty();
Why it breaks:
any disables type checking. You lose compile-time safety.
Correct approach:
constresult=someFunction()asUser;
Use a specific type instead of any.
Mistake 3: Ignoring null in DOM queries
What you might do:
constinput=document.getElementById("username")asHTMLInputElement;
input.value="Alex";
Why it breaks:
If the element does not exist, the value is null and accessing properties causes an error.
Correct approach:
constinput=document.getElementById("username")asHTMLInputElement|null;
if (input) {
input.value="Alex";
}
Handle the nullable case.
Troubleshooting
If TypeScript still shows an error, confirm that your asserted type matches the actual structure of the value.
If you see runtime errors after compiling successfully, check that your assertion reflects the real runtime type.
If JSX parsing fails, switch from angle brackets to as syntax.
If strict null checks complain, include | null and guard the value.
Quick recap
- Use
as Typeto tell TypeScript how to treat a value - Assertions do not perform runtime validation
- Narrow values with type guards before asserting
- Avoid
as anyunless absolutely necessary - Handle
nullwhen working with DOM elements - Prefer
asover angle brackets in modern projects
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot