Production-Grade TypeScript: Concepts You Missed

Strictness is Non-Negotiable

In a professional setting, strict: true is the baseline. But what about noUncheckedIndexedAccess?

noUncheckedIndexedAccess

By default, TS lies about array access.

const users: string[] = [];
const user = users[0]; // Type is string, but runtime is undefined!

Enable noUncheckedIndexedAccess: true in tsconfig.json. Now user is string | undefined.

Generics & Constraints

Don't just use T. Constrain it.

// Bad: T could be anything
function getLength<T>(arg: T): number { ... }

// Good: T must have a length property
function getLength<T extends { length: number }>(arg: T): number {
  return arg.length;
}

The infer Keyword

Conditional types with infer allow you to extract types from within other types.

Use Case: Extracting the return type of a function (manually, though ReturnType exists).

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

function getData() {
  return { id: 1, name: "Ajay" };
}
type Data = MyReturnType<typeof getData>; // { id: number, name: string }

Type Guards

Don't cast using as. Validate.

function isError(err: unknown): err is Error {
  return err instanceof Error;
}

try {
  // ...
} catch (err) {
  if (isError(err)) {
    console.log(err.message); // Safe access
  }
}