Data types and type casting in TypeScript

By Nitin Pandit | Views: 774

TypeScript is a superset of JavaScript, and as such, it inherits all of JavaScript's data types. In addition, TypeScript adds several new data types that are not available in JavaScript.

Here are some of the data types in TypeScript:

  1. Boolean: This data type represents a value that can be either true or false.
  1. Number: This data type represents a numeric value. TypeScript supports both integer and floating-point numbers.
  1. String: This data type represents a sequence of characters. Strings can be enclosed in single or double quotes.
  1. Array: This data type represents a collection of values of the same type. TypeScript arrays can be declared using square brackets [].
  1. Tuple: This data type represents a fixed-length array where each element can have a different type. Tuple elements are declared inside square brackets with the type of each element separated by a comma.
  1. Enum: This data type represents a set of named constants. Each constant in an enum is assigned a unique value.
  1. Any: This data type represents any value. Variables declared as any can have values of any type.
  1. Void: This data type represents the absence of a value. Functions that return nothing are declared as void.
  1. Null and Undefined: These data types represent null and undefined values, respectively.
  1. Never: This data type represents a value that never occurs. Functions that throw an error or enter an infinite loop are declared as returning never.

Type Casting in TypeScript

TypeScript provides a feature called type casting that allows you to change the type of a variable from one type to another. Type casting is also known as type assertion in TypeScript.

There are two ways to perform type casting in TypeScript:

Using the angle-bracket syntax:

let myVariable: any = "Hello World";

let length: number = (<string>myVariable).length;

In this example, we are declaring a variable named myVariable with the any type and initializing it with a string value. We are then using angle-bracket syntax to cast the myVariable to a string and then getting the length of the string.

Using the as keyword:

let myVariable: any = "Hello World";

let length: number = (myVariable as string).length;

In this example, we are using the as keyword to cast the myVariable variable to a string and then getting the length of the string.

TypeScript type casting is a way to tell the TypeScript compiler that we know the type of a variable, and we want to use it as that type. Type casting is useful when working with dynamic data types or when interfacing with JavaScript libraries that do not have type definitions.

Thank you for your feedback!