TypeScript Essentials
Advanced TypeScript Types
Advanced TypeScript Types
Section titled “Advanced TypeScript Types”Master TypeScript’s advanced type system features.
Union Types
Section titled “Union Types”type StringOrNumber = string | number;
function process(value: StringOrNumber) { if (typeof value === "string") { return value.toUpperCase(); } return value * 2;}Intersection Types
Section titled “Intersection Types”type Person = { name: string };type Employee = { employeeId: string };
type Staff = Person & Employee;
const staff: Staff = { name: "Alice", employeeId: "E123"};Type Guards
Section titled “Type Guards”// typeof guardfunction isString(value: unknown): value is string { return typeof value === "string";}
// instanceof guardfunction isDate(value: unknown): value is Date { return value instanceof Date;}
// in guardinterface Dog { bark(): void }interface Cat { meow(): void }
function speak(animal: Dog | Cat) { if ("bark" in animal) { animal.bark(); } else { animal.meow(); }}Utility Types
Section titled “Utility Types”interface User { name: string; age: number; email: string;}
// Partial - all properties optionaltype PartialUser = Partial<User>;
// Required - all properties requiredtype RequiredUser = Required<User>;
// Readonly - all properties readonlytype ReadonlyUser = Readonly<User>;
// Pick - select specific propertiestype UserName = Pick<User, "name" | "email">;
// Omit - exclude specific propertiestype UserWithoutEmail = Omit<User, "email">;
// Record - key-value mappingtype UserMap = Record<string, User>;Conditional Types
Section titled “Conditional Types”type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // truetype B = IsString<number>; // false
// Infer keywordtype ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function greet() { return "hello"; }type GreetReturn = ReturnType<typeof greet>; // stringTemplate Literal Types
Section titled “Template Literal Types”type Color = "red" | "green" | "blue";type Size = "small" | "medium" | "large";
type Style = `${Size}-${Color}`;// "small-red" | "small-green" | ... | "large-blue"Mapped Types
Section titled “Mapped Types”type Optional<T> = { [K in keyof T]?: T[K];};
type ReadonlyKeys<T> = { readonly [K in keyof T]: T[K];};
// With key remappingtype Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];};Congratulations!
Section titled “Congratulations!”You’ve completed the TypeScript tutorial! Continue with:
Tutorials