Open In App

TypeScript Assertions Type

Last Updated : 01 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • variableName: This is the name of the variable you want to assign the asserted value to.
  • AssertedType: This is the type you are telling TypeScript to treat the value as. It should be a valid TypeScript type.
  • value: This is the value that you want to assert the type for. It can be a variable, an expression, or a function return value.

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.

Javascript




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.

Javascript




// 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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads