Table of contents
1.
Introduction
2.
Type casting in Typescript
3.
Syntax of Type casting in Typescript
4.
Why is type casting in typescript needed?
5.
Type casting: Using the as Keyword
6.
Type casting: Using the <> Operator
7.
Typescript: Type Conversion
7.1.
Type Casting a string type to a number using ‘as’
7.2.
Type Casting a string type to a number using ’<>’
7.3.
Type Casting a number type to a string using ’as’
7.4.
Type Casting a number type to a string using ’unknown’
8.
Frequently Asked Questions
8.1.
In TypeScript, how does the casting method work?
8.2.
What is typecast function in TypeScript?
8.3.
What is typecast in TypeScript array?
8.4.
How do you typecast to a string in TypeScript?
8.5.
What is the use of typecast?
9.
Conclusion
Last Updated: May 4, 2024
Easy

Type Casting in TypeScript

Author Sneha Mallik
0 upvote

Introduction

Typecasting, commonly known as type conversion, is a technique for transforming one type into another in TypeScript. Typecasting exists, even though they don't work in the same way in strong programming languages. It exists in Object-oriented programming, but it does not exist in JavaScript. Surprisingly, the typescript programming language, which compiles to JavaScript, has the idea of casting. 

Type Casting in TypeScript

Since the variables in JavaScript have dynamic types, there is no concept of type casting in Javascript. TypeScript, on the other hand, assigns a type to every variable. Converting a variable from one type to another is possible with type casting in Typescript.

Type casting in TypeScript can be done with the ‘as’ keyword or the ‘<>’ operator. We'll look at type casting in typescript programming language in this blog.

Type casting in Typescript

The following types are supported by Typescript:

1)The built-in type(basic examples- number, string, boolean, and special type examples- any, unknown)

2)The additional type(examples- collections like ‘enum’ and even user-defined types)

Here's your problem of the day

Solving this problem will increase your chance to get selected in this company

Skill covered: Programming

How do you create a function in JavaScript?

Choose another skill to practice

Syntax of Type casting in Typescript

There are two types of syntax for type casting.

  • let A: number = (<string> B).length;
  • let A: number = (B as string).length;

Why is type casting in typescript needed?

Type casting assists in the conversion of types and provides predictable (expected) outcomes. 

For instance -

  • A number and a string are concatenated in type casting.
  • For formatting and display, type casting converts arrays of numbers to strings.

Type casting: Using the as Keyword

Using the ‘querySelector()’ method, the following code selects the first input element:

let input = document.querySelector('input["type="text"]');

The following code generates a compiler error since the returned type of the document.querySelector() method is the Element type:

console.log(input.value);

The reason for this is that the Element type needs a value property. Only the HTMLInputElement type has it.

To fix this, utilize type casting to convert the Element to HTMLInputElement by using the ‘as’ keyword, as seen below:

let input = document.querySelector('input[type="text"]') as HTMLInputElement;

The HTMLInputElement type is now assigned to the input variable. As a result, there will be no errors if you access its value property. The code below works:

console.log(input.value);

When we access the property, we can cast the Element to HTMLInputElement as following:

let enteredText = (input as HTMLInputElement).value;

It's important to remember that the HTMLInputElement type is derived from the HTMLElement type, which is derived from the Element type. This form of casting is also known as down casting when you cast HTMLElement to HTMLInputElement.

It is also possible to perform a down casting. Consider the following scenario:

let el: HTMLElement;
el = new HTMLInputElement();

The type of the el variable in this example is HTMLElement. Since the HTMLInputElement type is a subclass of the HTMLElement type, we can assign it an instance of HTMLInputElement type.

The following is the syntax for changing a variable from typeA to typeB:

let a: typeA;
let b = a as typeB;

Type casting: Using the <> Operator

In addition to the ‘as’ keyword, the <> operator can be used to carry out type casting. Consider the following scenario:

let input = <HTMLInputElement>document.querySelector('input[type="text"]');
console.log(input.value);

The following is the syntax for type casting with the <> operator:

let a: typeA;
let b = <typeB>a;

Typescript: Type Conversion

The capacity to change from one data type to another is known as type conversion. TypeScript has built-in functions for converting between types.

Type Casting a string type to a number using ‘as’

Example: A Typescript program that uses the 'as' keyword to cast a string type to a number.

//initializing the flower variable which is of string type
let flower: string = "Rose" ;

//initializing the length variable which is of number type
let stringLength: number = (flower as string).length ;
console.log('The length of the string is: ', stringLength) ;

 

'Flower' and 'stringLength' are initialized in string and number types, respectively, in this code. Using the typecasting approach, the length of the string inside the variable flower is stored in the variable length. The length of the string taken will be displayed when the code is executed.

Type Casting a string type to a number using ’<>’

Example: A Typescript program that uses the '<>' operator to cast a string type to a number.

//initializing the flower variable which is of string type
let flower: string = "Marigold" ;

// initializing the length variable which is of number type
let stringLength: number = (<string> flower).length ;
console.log('The length of the string is: ', stringLength) ;

 

'Flower' and 'stringLength' are initialized in string and number types, respectively, in this code. Using the typecasting approach, the length of the string inside the variable flower is stored in the variable length. The approach of this code is different from that of the previous code in the way it is typecasted. Instead of using <> in the first code, 'as' is used in the previous code. The length of the string taken will be displayed when the code is executed. 

Type Casting a number type to a string using ’as’

Example: A Typescript program that uses the 'as' keyword to cast a number type to a string.

//initializing the length variable which is of number type
let stringLength: number = 22 ;

//initializing the flower variable which is of string type
let flower: string = (stringLength as string) ;
console.log('The length of the string is: ', stringLength) ;

 

'stringLength' and 'Flower' are initialized in number and string types, respectively. However, the issue with this code is the type that must be cast. The number type is attempting to cast to a string in this case. However, as demonstrated below, this will result in an error.

As an alternative, we'll modify the code as shown in the following step.

Type Casting a number type to a string using ’unknown’

Example: A Typescript program that uses the 'unknown' keyword to cast a number type to a string.

//initializing the length variable which is of number type
let stringLength: number = 22 ;

//initializing the flower variable which is of string type
let flower: string = (stringLength as unknown) as string ;
console.log('The length of the string is: ', stringLength) ;

 

The cast type is first set to unknown and then typecasted in this code. As a result, the error will not appear as it does in the above code output.

Frequently Asked Questions

In TypeScript, how does the casting method work?

Typescript is a typed language that improves the development experience, which is why it is preferred over Javascript. It mainly enhances the user experience by detecting and correcting mistakes before the developer begins deploying code.

What is typecast function in TypeScript?

Typecast function in TypeScript explicitly converts a value from one data type to another, ensuring type compatibility and preventing runtime errors.

What is typecast in TypeScript array?

Typecast in TypeScript array converts elements to a specific data type, ensuring uniformity and enabling type-specific operations on array elements.

How do you typecast to a string in TypeScript?

To typecast to a string in TypeScript, use the as keyword or the <string> syntax to explicitly specify the desired data type.

What is the use of typecast?

Typecast ensures data integrity and consistency by converting values to compatible types, facilitating accurate operations and preventing runtime errors in TypeScript.

Conclusion

In this blog, we have learned the concepts of type casting in typescript and how they are used with examples, syntax and working. We can type cast a variable to convert it from one type to another. Use the ‘as’ keyword or the ‘<>’ operator for type castings.

Take a look at our Typescript archives section and see many more interesting topics related to it. Apart from that, you can refer to our Guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, Javascript, System Design, etc.

Credits: GIPHY

Happy Developing!

Live masterclass