In TypeScript, like in many programming languages, data types can be broadly categorized into two main groups:
Primitive types
Non-Primitive (reference) types
Represents textual values or sequence of characters.
let para: string = "This is a Paragraph text"; let username: string = "Alice Collin";
let count: number = 30; let age: number = 48; let orderNumber: number = 334455;
Represents numeric values.
let age: number = 20; let isAdult: boolean = age > 18; console.log(isAdult) // true
let nullValue: null = null; let undefinedValue: undefined = undefined; console.log(nullValue); // null console.log(undefinedValue); // undefined
Represents a boolean value (true or false).
let uniqueSymbol: symbol = Symbol("unique");
let bigIntValue: bigint = 33n;
Represent the absence of a value.
Represents a unique identifier.
let numberList: number[] = [1, 2, 3, 4, 5, 6]; console.log(numberList);
Represents integers of arbitrary precision.
let employeeProfile: object = { fullName: "Alice Collin", department: 'HR' }; // print object output in console console.log(employeeProfile); // { fullName: "Alice Collin", department: 'HR' } // print individual value in console console.log(employeeProfile.fullName); // Output: "Alice Collin" console.log(employeeProfile.department); // Output: 'HR'
// using arrow function let multiple: (num1: number, num2: number) => number = (num1, num2) => num1 * num2; console.log(multiple(10, 12)); // 120 // using traditional function function multiple(num1: number, num2: number) { return num1 * num2; } console.log(multiple(10, 12)); // 120
let age: number = 33; let username: string = "Alice Collin"; let isAdult: boolean = age > 18; let dynamicUserValue: any = isAdult ? username : age; console.log(dynamicUserValue) // `Alice Collin` -> in current scenario, if age less than 18 then it will print -> age.
Non-primitive types are more complex data structures. They are mutable, meaning their values can be changed, and they are often created using constructors.
class Student { constructor(public name: string, public age: number) {} } let student: Student = new Student("Alice Collin", 20); console.log(student.name); console.log(student.age);
interface Image { src: string; width: number; height: number; } let point: Point = { src: "image-url", width: 50, height: 100 }; console.log(point);
Represents an ordered collection of elements.
enum Permission { ADMIN, IAM, GROUP_ADMIN, } let permission: Permission = Permission.ADMIN; console.log(permission);
Represents any non-primitive type.
Specifies the signature of a function.
A type that can hold any value. Avoid using it when possible.
Represents a blueprint for creating objects.
Represents a contract for the shape of an object.
Represents a set of named constants.