Type Casting in TypeScript

Job-ready Online Courses: Dive into Knowledge. Learn More!

One of the essential features of TypeScript is typecasting, which allows developers to convert one data type to another. Whether converting a string to a number, an object to a particular class, or an interface to another, type casting can be used in a variety of situations. This article will provide an overview of typecasting in TypeScript, including its syntax, types of casting, and examples of how to use it.

Type Casting Syntax

Type Casting in TypeScript is performed using the “as” keyword. The “as” keyword is followed by the target data type enclosed in angle brackets. Here is an example of how to perform typecasting in TypeScript:

let DataFlair_myVariable: any = '123';
let DataFlair_myNumber: number = DataFlair_myVariable as number;
console.log(typeof DataFlair_myNumber); // "number"

In the above example, we first declared a variable “DataFlair_myVariable” of type “any” and assigned it a string value “123”. We then typecasted “DataFlair_myVariable” using the “as” keyword. We specified the target data type as “number.” The result of the type casting is assigned to “DataFlair_myNumber” variable, which now has a data type of “number.” We then printed the type of “DataFlair_myNumber” using the “typeof” operator, which returns “number.”

Types of Type Casting

TypeScript provides two types of type casting: explicit type casting and implicit type casting.

Explicit Type Casting

Explicit type casting is when a developer specifies the target data type using the “as” keyword. It is useful when a developer wants to convert a value to a specific data type. Here is an example of how to perform explicit typecasting in TypeScript:

let DataFlair_myVariable: any = '123';
let DataFlair_myNumber: number = DataFlair_myVariable as number;
console.log(typeof DataFlair_myNumber); // "number"

In the above example, we explicitly cast “DataFlair_myVariable” to a “number” data type using the “as” keyword.

Implicit Type Casting

Implicit type casting is when TypeScript automatically converts one data type to another without the developer’s explicit instructions. It is useful when a developer wants to avoid type errors and improve code readability. Here is an example of how to perform implicit typecasting in TypeScript:

let DataFlair_myNumber: number = 123;
let DataFlair_myString: string =
 'The value of myNumber is ' + DataFlair_myNumber;
console.log(typeof DataFlair_myString); // "string"

In the above example, we implicitly cast “DataFlair_myNumber” to a “string” data type by concatenating it with another string value.

Type Assertion

Type assertion is another way to perform typecasting in TypeScript. It is similar to explicit type casting but uses a different syntax. Type assertion can be performed in angle bracket syntax and “as” syntax.

Angle Bracket Syntax

Angle bracket syntax is an older way of performing type assertion in TypeScript. It involves enclosing the value to be cast in angle brackets followed by the target data type. Here is an example of how to perform type assertion using angle bracket syntax:

let DataFlair_myVariable: any = '123';
let DataFlair_myNumber: number = <number>DataFlair_myVariable;
console.log(typeof DataFlair_myNumber); // "number"

In the above example, we used angle bracket syntax to perform type assertion on “DataFlair_myVariable” and cast it to a “number” data type.

“As” Syntax

“As” syntax is a newer way of performing type assertion in TypeScript. It involves using the “as” keyword followed by the target data type. Here is an example of how to perform type assertion using “as” syntax:

let DataFlair_myVariable: any = '123';
let DataFlair_myNumber: number = DataFlair_myVariable as number;
console.log(typeof DataFlair_myNumber); // "number"

In the above example, we used “as” syntax to perform type assertion on “DataFlair_myVariable” and cast it to a “number” data type.

Type Casting with Interfaces

Type casting can also be used with interfaces in TypeScript. Interfaces are used to specify an object’s structure. Type casting can be used to convert an object to a specific interface. Here is an example of how to use type casting with interfaces in TypeScript:

interface DataFlair_Person {
 name: string;
 age: number;
}


let myPerson: DataFlair_Person = { name: 'John', age: 25 };
let myObject: object = myPerson;
let myPersonAgain: DataFlair_Person = myObject as DataFlair_Person;
console.log(myPersonAgain.name); // "John"
console.log(myPersonAgain.age); // 25

In the above example, we defined an interface called “DataFlair_Person” that has two properties: “name” and “age.” We then declared an object “myPerson” that conforms to the “DataFlair_Person” interface. Then assigned “myPerson” to a variable “myObject” of type “object.” We then performed type casting on “myObject” and converted it to the “DataFlair_Person” interface using the “as” keyword. The result of the type casting is assigned to “myPersonAgain” variable, which now has a data type of “DataFlair_Person.” We then printed the “name” and “age” properties of “myPersonAgain” object.

Type Casting with Classes

Type casting can also be used with classes in TypeScript. Classes are used to create objects with methods and properties. Type casting can be used to convert an object to a specific class. Here is an example of how to use type casting with classes in TypeScript:

class DatFlair_Animal {
 name: string;
 constructor(name: string) {
   this.name = name;
 }
}


class Dog extends DatFlair_Animal {
 breed: string;
 constructor(name: string, breed: string) {
   super(name);
   this.breed = breed;
 }
}


let myAnimal: DatFlair_Animal = new DatFlair_Animal('Leo');
let myDog: Dog = myAnimal as Dog;
console.log(myDog.name); // "Leo"
console.log(myDog.breed); // undefined

The above example defined two classes: “DataFlair_Animal” and “Dog.” “Dog” class extends “DataFlair_Animal” class and adds a “breed” property. We then declared a “DataFlair_Animal” object “myAnimal” and assigned it to a variable of type “DataFlair_Animal.” We then performed type casting on “myAnimal” and converted it to “Dog” class using the “as” keyword. The result of the type casting is assigned to “myDog” variable, which now has a data type of “Dog.” We then printed the “name” and “breed” properties of “myDog” object. Since “myAnimal” object is not an instance of “Dog” class, the “breed” property is undefined.

Why is type casting in typescript needed?

Type casting in TypeScript is needed when we want to treat an expression as a different type than what TypeScript has inferred it to be. This can happen when working with complex data types or when using external libraries that don’t have type definitions.

For example, suppose we have an object with several properties, but we only need to use one of those properties:

const DataFlair_person = { name: 'Alice', age: 30 };
console.log(DataFlair_person.name);

Output

Alice

In the above example, TypeScript infers the type of DataFlair_person to be an object with two properties: name of type string and age of type number. When we try to access the name property, TypeScript knows it exists and has a string type, so typecasting is unnecessary.

However, if we were to use a library that doesn’t have type definitions, we might need to use type casting to treat the library’s output as a specific type:

const result = someLibraryFunction();
const data = result as DataFlair_MyDataType;

In the above example, someLibraryFunction returns data of an unknown type, but we know it should conform to the DataFlair_MyDataType interface. By using type casting with the as keyword, we can treat the result as the desired type and ensure that TypeScript checks that the properties and methods we access are correct.

Type casting can also be useful when working with union types or when dealing with generic types. It can help ensure the code is type-safe and prevent errors at compile time.

Overall, typecasting in TypeScript is a powerful tool that can help ensure that the code is correct and type-safe. It is especially useful when working with external libraries or complex data types.

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

TypeScript provides the unknown type to represent values of any type. When type casting a number type to a string using unknown, we first cast the number to be unknown and then to string. This ensures that TypeScript checks the type at runtime and prevents type-related errors.

For example, suppose we have a variable num of type number, and we want to cast it to a string:

let DataFlair_num: number = 42;
let DataFlair_str: string = DataFlair_num as unknown as string;

In the above example, we first cast DataFlair_num to be unknown using as unknown, then we cast it to string using as a string. This tells TypeScript to treat DataFlair_num as unknown, allowing it to perform runtime type checking and then treat the resulting value as a string.

It is important to note that type casting with unknown can be less type-safe than casting with other types. This is because the unknown has no properties or methods that can be accessed without performing a type check.

Overall, type casting a number type to a string using unknown can be useful in certain situations where type safety is a concern. However, using it carefully and only when necessary is important to prevent potential runtime errors.

Casting with ‘as’

In TypeScript, the as keyword can be used for typecasting. It allows developers to explicitly convert a variable of one type to another, which can be useful when working with complex data types or when using external libraries that don’t have type definitions.

For example, suppose we have a variable str of type string, but we need to treat it as a number:

const DataFlair_str: string = '42';
const DataFlair_num: number = DataFlair_str as number;

In the above example, we use the as keyword to cast DataFlair_str to a number. This tells TypeScript to treat DataFlair_str like a number, allowing us to perform mathematical operations or pass it to functions that expect a number argument.

Type casting with as can also be useful when working with union types, where a value could be of multiple types:

type DataFlair_MyType = string | number;


function myFunction(input: DataFlair_MyType): void {
 const DataFlair_str: string = input as string;
 console.log(DataFlair_str.length);
}

In the above example, we define a type called DataFlair_MyType which could be a string or a number. In the myFunction function, we use the as keyword to cast input to a string, allowing us to access its length property. This ensures that TypeScript checks that the properties and methods we access are correct.

Overall, type casting, as in TypeScript can be a powerful tool to help ensure the code is correct and type-safe. It is especially useful when working with external libraries or complex data types. However, using it carefully and only when necessary is important to prevent potential runtime errors.

Conclusion

Type casting is a powerful feature in TypeScript that allows developers to convert one data type to another. Whether converting a string to a number, an object to a particular class, or an interface to another, type casting can be used in a variety of situations.TypeScript provides two types of type casting: explicit type casting and implicit type casting. Type casting can also be used with interfaces and classes in TypeScript. With the help of typecasting, developers can write type-safe and maintainable code.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *