#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 45 of 48easy

Type 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

DeclarationAssertion
TypeScript validatesYou assert
Compile-time checkTrust developer
Catches errorsMay 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
}