06 type manipulation

This is where TypeScript stops being “JavaScript with annotations” You build new types from existing ones instead of writing them twice

Table of Contents

keyof and typeof

interface Target {
  host: string;
  port?: number;
}

type TargetKeys = keyof Target;
type PortType = Target["port"];
const inferred = "hello";
type HostType = typeof inferred;

keyof produces a union of property names T["key"] indexes a type typeof in a type position reads the type of a value

Conditional types

type MaybeArray<T> = T extends Array<infer U> ? U : T;

This is a type-level if infer U extracts the element type from an array Conditional types distribute over unions when the checked type is naked

Mapped types

type Mapped<T> = { [K in keyof T]: T[K] };

Mapped types iterate over keys Partial , Readonly , and Record are built this way

Template literals

type EventName = `on${Capitalize<string>}`;

Template literal types build string literal unions at the type level Combine with Uppercase , Lowercase , Capitalize , and Uncapitalize

Utility types

type PartialTarget = Partial<Target>;
type RequiredTarget = Required<Target>;
type ReadonlyTarget = Readonly<Target>;
type TargetMap = Record<"dev" | "prod", Target>;
type Preview = Pick<Target, "host">;
type WithoutHost = Omit<Target, "host">;

Use these before writing your own They are globally available and covered in the reference Partial makes every property optional Required is the opposite Pick and Omit select or remove keys

Posted