TypeScript offers a robust type system that includes both basic and advanced types. Here’s an overview of the different types available in TypeScript:
Basic Types
Number: Represents all numbers (both integer and floating-point).
let num: number = 10;
String: Represents text data.
let name: string = "Hello John";
Boolean: Represents true/false values.
let isTrue: boolean = true;
Array: Represents a collection of elements of a specific type.
let numArray: number[] = [1, 2, 3];
let strArray: string[] = ["a", "b", "c"];
Tuple: Represents an array with a fixed number of elements of specified types.
let rule: [number, string] = [1, "Admin"];
Enum: Represents a set of named constants.
enum Color { Red, Green, Blue }
let c: Color = Color.Green;
Any: Represents any type and disables type checking for that variable.
let data: any;
data = "Hello";
console.log(data);
data = 15;
console.log(data);
Void: Represents the absence of any type, commonly used as the return type for functions that do not return a value.
function message(): void {
console.log("This returns nothing");
}
Null and Undefined: Represents the absence of a value. By default, null
and undefined
are subtypes of all other types.
let n: null = null;
let u: undefined = undefined;
Never: Represents the type of values that never occur (e.g., a function that always throws an error).
function error(message: string): never {
throw new Error(message);
}
Advanced Types
Union Types: Represents a value that can be one of several types.
let value: string | number;
value = "Hello";
value = 45;
Intersection Types: Combines multiple types into one.
interface A { a: number; }
interface B { b: string; }
let ab: A & B = { a: 45, b: "Hello" };
Type Aliases: Creates a new name for a type.
type StringOrNumber = string | number;
let value: StringOrNumber;
value = "Hello";
value = 45;
Literal Types: Represents specific values.
let literal: "Hello" | "world";
literal = "Hello"; // valid
literal = "world"; // valid
// literal = "Hi"; // invalid
Nullable Types: Allows a type to be null
or undefined
.
let nullableString: string | null | undefined;
nullableString = "hello";
nullableString = null;
nullableString = undefined;
Function Types: Describes the type of a function.
let myFunction: (x: number, y: number) => number;
myFunction = (x, y) => x + y;
Type Assertions: Tells the compiler to treat a value as a specific type.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Interfaces: Describes the shape of an object.
interface Person {
name: string;
age: number;
}
let person: Person = { name: "John", age: 25 };