EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript cast
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript cast

TypeScript cast

Introduction to TypeScript cast

The following article provides an outline for the TypeScript cast. Typecasting, which is also known as type conversion, helps in converting one type into another. Even though they don’t work alike in strong programming languages, it exists. That is, in Object-oriented programming, typecasting exists but in the case of JavaScript, it doesn’t have the typecasting concept. Surprisingly, typescript language that compiles into the programming language JavaScript has the concept of casting. In this article, we will be dealing with typecasting in the typescript programming language.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Typecasting can be done using two syntaxes, as shown below.

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

How does the cast method work in TypeScript?

As we all know, there will be a particular reason why we choose a programming language.

In the case of Typescript, it is a typed language that boosts the development experience, which is the main reason it is used over JavaScript. The main way it boosts the experience is by catching errors as well as offering fixes before the developer starts deploying code.

Normally, we will assign types like strings, Boolean, numbers, structures, and so forth to different variables, as mentioned below.

let fruit: string = 'apple';
let mark: number = 35;
let workdone: boolean = false;

Now, let us consider a scenario where we have to assign the variable fruit’s string length to a variable that is initialized as the number. In this situation, what will you do?

let fruit: string = 'apple';
let len: number = ??’

This is the situation where we use the typecasting concept. Either typecast the variable explicitly to the string type and find the length. That is, typecasting can be done by prepending the fruit variable using the type enclosed in the angle brackets as depicted below.

let fruit: string = 'apple';
let len: number = (<string> fruit).length;

Another way to do the typecasting is by adding ‘as’ to the syntax.

let fruit: string = 'apple';
let len: number = (fruit as string).length;

Even though both these methods can be used for typecasting, typescript in React will support the typecasting using ‘as’ only. Also, there are some situations where typecasting is not possible with certain types. That is, consider the situation where a number has to be converted to a string, as shown below.

let len: number = 35;
let fruit: string =( len as string);

If we try to compile this, what will happen?

Yes. The compiler will throw an error as the string type cannot be overlapped to a number.

For solving this, first, we have to typecast lento unknown and then to string as shown below.

let len: number = 35;
let fruit: string =( len as unknown) as string;

Note:

In typescript, it is possible to downcast as well as upcast the types.

Examples

In this section, we will be looking into some working samples on casting in typescript.

Program: Typescript program that casts a string type to number using ‘as’.

//initialise fruit variable which is of string type
let fruit: string = "apple" ;
// initialise len variable which is of number type
let len: number = (fruit as string).length ;
console.log('The length of the string is: ', len) ;

Output:

TypeScript cast output 1

In this program, a variable fruit and len are initialized in string and number type, respectively. The length of the string inside the variable fruit is stored in the variable len using the typecasting method. On executing the code, the length of the string will be displayed.

Program: Typescript program that casts a string type to number using <>.

//initialise fruit variable which is of string type
let fruit: string = "apple" ;
//initialise fruit variable which is of string type
let len: number = (<string> fruit).length;
console.log('The length of the string is: ', len) ;

Output :

TypeScript cast output 2

In this program, a variable fruit and len are initialized in string and number type. The length of the string inside the variable fruit is stored in the variable len using the typecasting method. The difference between this program from the above program is the way it is typecasted. That is, in the first program, ‘as’ is used instead of <> in this program. However, on executing the code, the length of the string will be displayed.

As we have already mentioned in the working of typecasting, <> won’t work in React. If it is used in React, an error will be displayed, as shown below.

TypeScript cast output 3

Program: Typescript program that casts a number type to string using ‘as’.

//initialise len variable which is of number type
let len: number = 35;
//initialise fruit variable which is of string type
let fruit: string =( len as string);
console.log('The length of the string is: ', len);

Output:

output 4

In this program, a variable fruit and len are initialized in string and number type. But the problem with this program is the type that has to be cast. Here, the number type is trying to cast to a string. But, this will result in an error, as shown below.

output 5

let len: number

As a solution for this, we will be modifying the code as shown in the below program.

Program: Typescript program that casts a number type to string using ‘unknown’.

//initialise len variable which is of number type
let len: number = 35;
//initialise fruit variable which is of string type
let fruit: string =( len as unknown) as string;
console.log(fruit);

Output:

output 6

In this program, the type is set as unknown first, and it is then typecasted. So, the error won’t occur as in the above program output.

Conclusion

Typecasting is a technique that helps in converting one type into another. Even though it is not present in javascript, it is surprising that the typescript language that compiles into the programming language JavaScript has the concept of casting. In this article, different aspects such as syntax, working, and examples of typecasting are explained in detail.

Recommended Articles

We hope that this EDUCBA information on “TypeScript cast” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript let
  2. TypeScript typeof
  3. TypeScript Export Function
  4. TypeScript Dictionary
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more