TypeScript DataTypes
TypeScript provides several built-in data types. Here is a comprehensive list of the data types available in TypeScript:
Boolean
The boolean type represents logical values: true and false.
let isDone: boolean = false;Number
The number type represents both integer and floating-point numbers.
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;String
The string type represents textual data.
let color: string = "blue";
color = 'red';
let fullName: string = `John Doe`;Array
The array type represents a list of elements of a specific type.
let list: number[] = [1, 2, 3];
let fruits: Array<string> = ["apple", "banana", "cherry"];Tuple
The tuple type allows you to express an array where the type of a fixed number of elements is known, but need not be the same.
let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // ErrorEnum
The enum type is a way of giving more friendly names to sets of numeric values.
enum Color {
Red,
Green,
Blue,
}
enum Color {Red, Green, Blue}
let c: Color = Color.Green;Any
The any type is a powerful way to work with existing JavaScript, allowing you to opt-out of type-checking.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a booleanVoid
The void type is used to indicate the absence of any type, commonly used as the return type of functions that do not return a value.
function warnUser(): void {
console.log("This is a warning message");
}Null and Undefined
The null and undefined types have their own values null and undefined, respectively.
let u: undefined = undefined;
let n: null = null;Never
The never type represents the type of values that never occur. For example, a function that always throws an exception or one that never returns.
function error(message: string): never {
throw new Error(message);
}Object
The object type represents non-primitive types, i.e., anything that is not number, string, boolean, symbol, null, or undefined.
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OKType Assertion
Type assertions are a way to tell the compiler that you know more about the type of a value than it does.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;Conclusion
TypeScript provides a rich set of data types that can be used to define variables, functions, and interfaces. By using these data types effectively, you can write more robust and maintainable code.