Skip to content
TypeScript Essentials

Advanced TypeScript Types

Beginner Lesson 9 of 9

Master TypeScript’s advanced type system features.

type StringOrNumber = string | number;
function process(value: StringOrNumber) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value * 2;
}
type Person = { name: string };
type Employee = { employeeId: string };
type Staff = Person & Employee;
const staff: Staff = {
name: "Alice",
employeeId: "E123"
};
// typeof guard
function isString(value: unknown): value is string {
return typeof value === "string";
}
// instanceof guard
function isDate(value: unknown): value is Date {
return value instanceof Date;
}
// in guard
interface Dog { bark(): void }
interface Cat { meow(): void }
function speak(animal: Dog | Cat) {
if ("bark" in animal) {
animal.bark();
} else {
animal.meow();
}
}
interface User {
name: string;
age: number;
email: string;
}
// Partial - all properties optional
type PartialUser = Partial<User>;
// Required - all properties required
type RequiredUser = Required<User>;
// Readonly - all properties readonly
type ReadonlyUser = Readonly<User>;
// Pick - select specific properties
type UserName = Pick<User, "name" | "email">;
// Omit - exclude specific properties
type UserWithoutEmail = Omit<User, "email">;
// Record - key-value mapping
type UserMap = Record<string, User>;
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
// Infer keyword
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function greet() { return "hello"; }
type GreetReturn = ReturnType<typeof greet>; // string
type Color = "red" | "green" | "blue";
type Size = "small" | "medium" | "large";
type Style = `${Size}-${Color}`;
// "small-red" | "small-green" | ... | "large-blue"
type Optional<T> = {
[K in keyof T]?: T[K];
};
type ReadonlyKeys<T> = {
readonly [K in keyof T]: T[K];
};
// With key remapping
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

You’ve completed the TypeScript tutorial! Continue with: