Skip to main content
CodingMarble

Interview questions and cheat sheets

TypeScript Cheat Sheet: Types, Generics and tsconfig

TypeScript adds a static type layer to JavaScript that is checked before the code runs and then erased. This cheat sheet gives you the types and patterns you reach for daily, each in a code block that compiles, plus the strict settings and the error messages you will meet first.

By CodingMarble · Published · 4 min read

Two colleagues discussing ideas at a whiteboard
Photo: ThisisEngineering on Unsplash

Basic types and functions

TypeScript infers types from values, so annotate where inference cannot help: function parameters, public return types and empty collections. The primitive types are string, number, boolean, bigint, symbol, null and undefined. Arrays are written T[], and a tuple fixes both the length and the type at each position.

TypeScript· Annotations, inference and a typed function
const count = 3;                         // inferred as number
let label: string = "total";
const tags: string[] = [];
const pair: [string, number] = ["age", 30];

function greet(name: string, greeting = "Hello"): string {
  return greeting + ", " + name;
}

function logAll(...items: number[]): void {
  items.forEach((n) => console.log(n));
}

console.log(greet("Asha"), count, label, tags, pair);
logAll(1, 2, 3);

Two modifiers appear constantly. A question mark after a property name makes it optional, so its type becomes the declared type or undefined, and you must handle the missing case before using it. The readonly modifier stops reassignment through that name, but it is only a compile-time check and does not freeze the object at runtime. Use Readonly or readonly arrays for data that should not be edited by the functions that receive it.

Types exist only at compile time. Nothing here validates data arriving at runtime from a network or a file, so a value typed as User from JSON.parse is a promise you made, not a fact the compiler checked.

Interfaces and type aliases

For object shapes the two are nearly interchangeable, and a consistent team convention matters more than the choice. Interfaces can be extended with extends, and declarations with the same name merge, which is how libraries add fields to global types. Type aliases can name anything: unions, tuples, mapped and conditional types, which an interface cannot express. A practical rule is to use interface for object shapes you expect others to extend, and type for everything else.

TypeScript· Extending an interface, naming a union, merging declarations
interface User {
  id: number;
  name: string;
  email?: string;            // optional
  readonly createdAt: Date;  // cannot be reassigned
}

interface Admin extends User {
  permissions: string[];
}

type Status = "active" | "suspended";
type ID = string | number;

interface Settings { theme: string }
interface Settings { compact: boolean }   // merges with the one above
const s: Settings = { theme: "dark", compact: true };

const admin: Admin = { id: 1, name: "Ravi", createdAt: new Date(), permissions: ["write"] };
const userStatus: Status = "active";
const id: ID = "u-1";
console.log(s, admin, userStatus, id);

Unions, narrowing and type guards

A union says a value is one of several types. Before you use a member that exists on only some of them, you narrow the type with a check the compiler understands: typeof, instanceof, equality, the in operator, or a shared literal property. The last pattern, a discriminated union, is the most robust: each variant carries a kind tag, and a switch over it narrows each branch. Assigning the leftover to never makes the compiler flag any variant you forgot to handle.

TypeScript· Narrowing, an exhaustive switch and a custom type guard
function format(v: string | number | null): string {
  if (v === null) return "none";
  if (typeof v === "number") return v.toFixed(2);
  return v.toUpperCase();
}

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(s: Shape): number {
  switch (s.kind) {
    case "circle": return Math.PI * s.radius ** 2;
    case "square": return s.size ** 2;
    default: {
      const unreachable: never = s;   // errors if a new kind is added and not handled
      return unreachable;
    }
  }
}

function isString(x: unknown): x is string {
  return typeof x === "string";
}

console.log(format(3.14159), area({ kind: "square", size: 4 }), isString("a"));

Optional chaining and the nullish coalescing operator work with narrowing. The expression user?.email stops with undefined if user is null or undefined, and value ?? fallback replaces only null and undefined, unlike ||, which also replaces 0 and an empty string. Both are checked by strict null checking, so they are the usual cure for the possibly undefined error.

A function whose return type is x is string tells the compiler that a true result means the argument is a string. The compiler trusts you, so the body must really perform the check; a wrong guard is a way to lie to the type system.

Generics and utility types

A generic is a type parameter that lets one function or type work over many types while keeping the relationship between input and output. Write first<T> so that an array of strings gives back a string, not any. A constraint with extends limits what callers may pass, and keyof T gives the property names of T, which makes a type-safe property getter possible.

TypeScript· Generic functions and a generic interface
function first<T>(items: T[]): T | undefined {
  return items[0];
}

function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

interface ApiResult<T> {
  data: T;
  error?: string;
}

const n = first([10, 20]);                       // number | undefined
const nameOnly = pluck({ id: 1, name: "Asha" }, "name");   // string
const res: ApiResult<string[]> = { data: ["a", "b"] };
console.log(n, nameOnly, res);

Resist adding type parameters you do not need. If a function uses T only once, such as in a single parameter with no relation to the result, a plain type is usually clearer. When a generic call infers something surprising, hover over the variable in your editor to see what the compiler decided, and pass the type explicitly, as in first<string>([]), only when inference truly cannot know.

Utility types transform existing types so you do not repeat them. Partial makes every property optional, which suits update payloads. Pick keeps only the named keys and Omit removes them. Record builds an object type from a key type and a value type. ReturnType extracts what a function returns, so a type can follow the code instead of being copied from it.

TypeScript· The utility types you will use most
interface Account {
  id: number;
  name: string;
  email: string;
}

type AccountPatch = Partial<Account>;                // all optional
type AccountPreview = Pick<Account, "id" | "name">;  // only id and name
type PublicAccount = Omit<Account, "email">;         // everything except email
type RoleMap = Record<"admin" | "viewer", string[]>;

function makeAccount() {
  return { id: 1, name: "Asha", email: "asha@example.com" };
}
type Made = ReturnType<typeof makeAccount>;

const patch: AccountPatch = { name: "Asha K" };
const roles: RoleMap = { admin: ["all"], viewer: ["read"] };
const made: Made = makeAccount();
console.log(patch, roles, made);

Enums, unknown, as const and satisfies

A union of string literals is usually the lighter alternative to an enum: it generates no runtime code, autocompletes, and its values are plain strings that serialise cleanly. Enums still make sense when you want a runtime object to iterate or a name for numeric codes. For a list of allowed values, as const freezes an array into a readonly tuple of literals, and indexing it with number derives the union from the same source.

On unknown versus any: both accept any value, but any switches checking off, so mistakes pass silently and spread, while unknown forces you to narrow before you use the value. Prefer unknown for data of uncertain shape, such as parsed JSON or a caught error. The satisfies operator checks that a value matches a type without widening the value's own type, so you keep precise information while still catching typos.

TypeScript· as const, unknown narrowing and satisfies
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];     // "admin" | "editor" | "viewer"
const current: Role = "editor";

function parse(json: string): unknown {
  return JSON.parse(json);
}
const raw = parse('{"count": 5}');
if (typeof raw === "object" && raw !== null && "count" in raw) {
  const data = raw as { count: number };
  console.log(data.count + 1);
}

const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
} satisfies Record<string, string | number[]>;

console.log(palette.red.map((c) => c / 255));   // still number[], not the wide union
console.log(palette.green.toUpperCase());       // still string
console.log(current);

Strict mode and tsconfig essentials

Turn on strict for every new project. It is a bundle of flags, including strictNullChecks, which stops null and undefined sneaking into other types, noImplicitAny, which rejects parameters whose type cannot be inferred, and strictFunctionTypes and strictPropertyInitialization. Two flags outside the bundle are worth adding: noUncheckedIndexedAccess, which makes array and index lookups include undefined, and noImplicitReturns. Enabling strict in an old codebase produces many errors at once, so move file by file or flag by flag.

JSON· A starting tsconfig.json for a bundled app (adjust target and module to your tooling)
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "dist"
  },
  "include": ["src"]
}

Practical tip: run npx tsc --noEmit in your project, or as a CI step. It type-checks without producing files, and it catches errors that a bundler or a transpiler such as Babel or esbuild never reports, because those tools strip types without checking them.

Common error messages and what they mean

The numeric code at the start of a message is stable and searchable, though the wording can change between compiler versions. Read the last line of a long message first: it usually names the exact property or type that does not fit.

Prompt· Frequent errors in plain words
TS2322: Type 'string' is not assignable to type 'number'.
  -> A value of one type was put where another is expected. Fix the value or the annotation.

TS2339: Property 'name' does not exist on type 'User'.
  -> Typo, or the property is missing from the type, or you need to narrow a union first.

TS2532 / TS18048: 'user' is possibly 'undefined'.
  -> A value can be undefined. Check it (if, ?.) or give a default before using it.

TS7006: Parameter 'x' implicitly has an 'any' type.
  -> noImplicitAny is on and the type cannot be inferred. Annotate the parameter.

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type.
  -> You indexed an object with a plain string. Use Record<string, T> or a keyof type.

TS2307: Cannot find module './util' or its corresponding type declarations.
  -> Wrong path, missing file extension setting, or a package without types (install its @types package).

Be careful with the escape hatches. The non-null assertion, value!, and a cast, value as Type, silence the compiler without proving anything, so a wrong one fails at runtime instead. Use them sparingly, and prefer a real check, such as an if statement, that the compiler can see.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.