In Typescript, Types play a crucial role in defining the shape and behaviour of variables, functions, and other entities in your code.
TypeScript introduces static type checking, which can help catch errors early during development and improve code quality.
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
Represents a boolean value (true or false).
let nullValue: null = null; let undefinedValue: undefined = undefined; console.log(nullValue); // null console.log(undefinedValue); // undefined
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.
Represent the absence of a values
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'
// define the shape of object using types. let employeeProfile: { name: string, dept: string, empId: number, onContract: boolean } = { name: "Alice Collin", dept: 'HR', empId: 123456, onContract: false }; // print employeeProfile object console.log(employeeProfile);
A type that can hold any value. Avoid using it when possible.
// 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
Represents any non-primitive type.
let unionValue: number | string = 42; unionValue = "forty-two"; console.log(unionValue); // forty-two
Defines the exact shape of an object.
interface Student { name: string; age: number; } interface School { standard: string; } let StudentProfile: Student & School = { name: "Alice Collin", age: 14, standard: "8th" }; console.log(StudentProfile);
// declare and initialized tuple let tuple: [string, string, number] = ["Alice", "HR", 23];
function greetMessage(): void { console.log("Hi, My Name is Alice"); }
Specifies the signature of a function.
enum DAYS { MONDAY, FRIDAY, SUNDAY, } let d: DAYS = DAYS.MONDAY;
Allows a variable to have multiple possible types.
Combines multiple types into one.
Represents an array with fixed-length and fixed-type elements.
Represents the absence of a type, most commonly used for functions that does not return any value.
Enum allows us to define named constants.