Open In App

TypeScript Assertions Type

TypeScript Assertions Type, also known as Type Assertion, is a feature that lets developers manually override the inferred or expected type of a value, providing more control over type checking in situations where TypeScript’s automatic type inference may not be sufficient.

Syntax

let variableName: AssertedType = value as AssertedType;  

Parameters

Example 1: In this example, the value is initially declared as any.(value as string) is a type assertion, telling TypeScript to treat the value as a string. This allows us to access the length property on the assumed string type. We log both the original value and the length to the console.






let value: any = "Hello, Geek!";
let len: number = (value as string).length;
  
console.log(`Value: ${value}`);
console.log(`Length: ${len}`);

Output

Value: Hello, Geek!
Length: 12

Example 2: In this example, defines an object ‘person’ with mixed types, then uses a type assertion to specify a more specific type for ‘personDetails‘ and displays its ‘name’ and ‘website’ properties.






// Define an object with mixed types
const person: any = {
    name: "GeeksforGeeks",
    website: "www.geeksforgeeks.org",
};
  
// Type assertion to specify
// a more specific type
const personDetails = person as {
    name: string;
    website: string;
};
  
// Access and display the person's details
console.log(`Name: ${personDetails.name}`);
console.log(`Website: ${personDetails.website}`);

Output:

Name: GeeksforGeeks
website: www.geeksforgeeks.org

Reference: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions

Article Tags :