3 min read
•Question 45 of 48easyType Assertions vs Type Declarations
Different ways to assign types.
What You'll Learn
- Type annotation (declaration)
- Type assertion
- Key differences
Type Annotation
Declares what type a variable should be.
code.tsTypeScript
// TypeScript validates the value
const user: { name: string } = {
name: "John"
};
// Error: missing property
const user2: { name: string; age: number } = {
name: "John"
};Type Assertion
Tells TypeScript to trust you about the type.
code.tsTypeScript
// You're telling TS "trust me"
const user = {} as { name: string };
// No error, but user.name is undefined!
// Common with DOM
const input = document.getElementById("email") as HTMLInputElement;Key Differences
| Declaration | Assertion |
|---|---|
| TypeScript validates | You assert |
| Compile-time check | Trust developer |
| Catches errors | May miss errors |
Best Practice
code.tsTypeScript
// Prefer declarations
const user: User = { name: "John", age: 30 };
// Use assertions sparingly
const data = parseJSON(str) as Config;
// Type guard is often better
if (isConfig(data)) {
// data is Config
}