SkillPilotAI

TypeScript: the next level

This module takes TypeScript past the basics: narrowing and discriminated unions model API states safely, generics make code reusable without losing types, and utility types, as const and satisfies derive and check types with less repetition.

22.1 The problem: data is possibly undefined

  • State has status "loading" | "success" | "error" with optional data and error.
  • render checks status === "success" and reads s.data.length.
  • TypeScript still says s.data is possibly undefined: nothing in the type links status to data.
TypeScript
type State = {  status: "loading" | "success" | "error";  data?: string[];  error?: string;}; function render(s: State) {  if (s.status === "success") {    return s.data.length;  }  return s.error;}
Output
$ npx tscstate.ts:9:12 - error TS18048:'s.data' is possibly 'undefined'.

22.2 Why the error?

  • There is no connection between status and data; data can be missing even on success.
  • All three situations are mixed into one object: a type design problem, not a logic problem.
  • Fix: a separate shape per situation, where status itself tells which fields exist.

22.3 Fix: discriminated union

  • Three object types, each with a fixed literal status (the discriminant).
  • The success shape has data required; the error shape has error required.
  • After the status === "success" check, TypeScript knows data exists: no error.
TypeScript
type State =  | { status: "loading" }  | { status: "success"; data: string[] }  | { status: "error"; error: string }; function render(s: State) {  if (s.status === "success") {    return `${s.data.length} items`;  }  if (s.status === "error") return s.error;  return "Loading...";} const cart = ["Shirt", "Socks"];console.log(render({ status: "success", data: cart }));
Output
2 items

22.4 How narrowing works

Narrowing flow
  1. 1.Start with a union type (string | number, or 3 states)

  2. 2.Add a check: typeof, instanceof, in, or compare a common field like status

  3. 3.Inside the block TypeScript shrinks the type to the exact member

  4. 4.Use that member's properties safely

The same idea makes if/switch on status fully type safe

CheckNarrowsExample
typeofPrimitivestypeof x === "number"
instanceofClass instanceserr instanceof Error
inObjects by property"data" in s
Literal fieldDiscriminated unionss.status === "success"

22.5 Generics: one function, any type

  • With any, the return type is also any and safety is gone.
  • <T> is a type placeholder; TypeScript fills the real type at the call.
  • first([499, 299]) makes T = number, first(["Pune", "Delhi"]) makes T = string, so toFixed and toUpperCase are both checked.
TypeScript
function first<T>(items: T[]): T {  return items[0];} const price = first([499, 299]);const city = first(["Pune", "Delhi"]); console.log(price.toFixed(2));console.log(city.toUpperCase());
Output
499.00PUNE

22.6 Generic type: ApiResponse<T>

  • Generics also work on types; the classic real example is an API response.
  • T decides the type of data while error stays string | null in every response.
  • ApiResponse<Product[]> gives autocomplete on res.data[0].name.
TypeScript
type ApiResponse<T> = {  data: T;  error: string | null;}; type Product = { id: number; name: string }; const res: ApiResponse<Product[]> = {  data: [{ id: 1, name: "Shirt" }],  error: null,}; console.log(res.data[0].name);
Output
Shirt

22.7 Constraints: T extends ...

  • Checkpoint: getLength<T> does not compile, because T could be a number or boolean with no length.
TypeScript
function getLength<T>(value: T) {  return value.length;}
Output
$ npx tsccheckpoint.ts:2:16 - error TS2339:Property 'length' does not exist on type 'T'.
  • Fix: T extends HasLength means T can be anything that has length: number.
  • Strings and arrays pass; passing a number is a compile error.
TypeScript
type HasLength = { length: number }; function getLength<T extends HasLength>(  value: T,) {  return value.length;} console.log(getLength("Pune"));console.log(getLength([10, 20, 30]));
Output
43

22.8 Utility types: Partial, Omit, Pick

  • Built-in generic types that create a new type from an existing one.
  • Partial<User>: every field optional (update forms).
  • Omit<User, "password">: remove fields (safe API response).
  • Pick<User, "id" | "name">: keep only the listed fields.
  • When User changes, all derived types update automatically.
TypeScript
type User = {  id: number;  name: string;  email: string;  password: string;}; type UserUpdate = Partial<User>;type PublicUser = Omit<User, "password">;type Card = Pick<User, "id" | "name">; const change: UserUpdate = { name: "Asha" };const card: Card = { id: 1, name: "Asha" };console.log(change, card);
Output
{ name: 'Asha' } { id: 1, name: 'Asha' }
UtilityWhat it doesTypical use
Partial<T>Makes every property optionalPATCH / update form
Omit<T, K>Removes the keys KPublic user without password
Pick<T, K>Keeps only the keys KCard or list item view

22.9 as const

  • as const makes values literal and readonly: ROLES is exactly ["admin", "buyer"], not string[].
  • type Role = (typeof ROLES)[number] derives the union from the array, so values live in one place.
  • canSell("guest") and ROLES.push("guest") are both errors.
TypeScript
const ROLES = ["admin", "buyer"] as const;type Role = (typeof ROLES)[number]; function canSell(role: Role) {  return role !== "buyer";} console.log(canSell("admin"));canSell("guest");ROLES.push("guest");
Output
$ npx tscroles.ts:9:9 - error TS2345: Argument oftype '"guest"' is not assignable ...roles.ts:10:7 - error TS2339: Property'push' does not exist on type 'readonly ...'Found 2 errors in the same file

22.10 satisfies

  • satisfies checks that a value matches a type without widening the value's own type.
  • With a normal annotation, routes.home would be the union string | { path: string }.
  • With satisfies, home stays string so toUpperCase works, and routes.profile is an error.
TypeScript
type Route = string | { path: string }; const routes = {  home: "/",  cart: { path: "/cart" },} satisfies Record<string, Route>; console.log(routes.home.toUpperCase());console.log(routes.cart.path);routes.profile;
Output
$ npx tscroutes.ts:10:8 - error TS2339: Property'profile' does not exist on type'{ home: string; cart: { path: string; }; }'.

22.11 Common mistakes

  • Using as (type assertion) to silence errors: the object has no id, TypeScript stays quiet, and toFixed crashes at runtime.
  • Use an annotation or satisfies instead so the missing id is a compile error.
  • TypeScript does not check data at runtime: types are removed after compiling. Validate API data with Zod.
TypeScript
// Wrong: as silences TypeScript, crash at runtimetype User = { id: number; name: string }; const user = { name: "Asha" } as User; console.log(user.id.toFixed(0));
TypeScript
// Right: annotation, missing id = compile errortype User = { id: number; name: string }; const user: User = { id: 1, name: "Asha" }; console.log(user.id.toFixed(0));

22.12 Interview tips

  • Generics are type parameters: one function or type works with many types, the real type is fixed at the call.
  • any turns checking off; generics carry type information from input to output.
  • Constraints (T extends X) control what T must have.
  • Discriminated unions + narrowing model loading/success/error states without optional-field bugs.
  • satisfies checks without widening; as only asserts and can hide bugs.