Hint
as Type tells TypeScript "trust me" — use sparingly; prefer type guards for safety
Type assertions tell TypeScript to treat a value as a specific type, overriding inferred or declared types. They do NOT perform runtime conversion.
// as syntax (preferred)
const input = document.getElementById('name') as HTMLInputElement;
input.value; // now valid — TypeScript trusts your assertion
// angle-bracket syntax (avoid in .tsx files)
const input2 = <HTMLInputElement>document.getElementById('name');
// Non-null assertion operator (!) — asserts value is not null/undefined
const el = document.querySelector('.btn')!; // you assert it exists
el.click();
// Double assertion — escape hatch when types seem incompatible
const x = someValue as unknown as TargetType;
When to use:
as HTMLInputElement) where TypeScript can't know the exact elementWhen NOT to use:
// ❌ Silencing a real bug
const user = getUser() as User; // getUser might return null!
// ✅ Proper guard
const maybeUser = getUser();
if (maybeUser !== null) {
const user: User = maybeUser; // safe
}
as assertion is a promise you make to TypeScript. Every assertion you write is a potential source of runtime errors if your assumption is wrong.