Data types and type casting in TypeScript
Here are some of the data types in TypeScript:
- Boolean: This data type represents a value that can be either true or false.
- Number: This data type represents a numeric value. TypeScript supports both integer and floating-point numbers.
- String: This data type represents a sequence of characters. Strings can be enclosed in single or double quotes.
- Array: This data type represents a collection of values of the same type. TypeScript arrays can be declared using square brackets .
- 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.
- Enum: This data type represents a set of named constants. Each constant in an enum is assigned a unique value.
- Any: This data type represents any value. Variables declared as any can have values of any type.
- Void: This data type represents the absence of a value. Functions that return nothing are declared as void.
- Null and Undefined: These data types represent null and undefined values, respectively.
- 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.