← Back to the journal

5 TypeScript Tricks That Make Your Code Safer

Small changes to the way you write TypeScript that can save you hours of debugging.

On this page

5 TypeScript Tricks That Make Your Code Safer

Reading position1 / 7
Editorial illustration for 5 TypeScript Tricks That Make Your Code Safer Without Making It Longer
AI-generated editorial illustration

One of the things I find interesting about TypeScript is that two developers can write almost identical JavaScript but end up with very different levels of type safety.

It doesn't necessarily come down to who writes more interfaces, uses more generics, or understands advanced conditional types.

Sometimes, it comes down to knowing which TypeScript feature to use in an otherwise ordinary piece of code.

Consider how often we work with configuration objects, API responses, arrays, application states, and function parameters. These are everyday development tasks, yet there are opportunities to improve them that are easy to overlook.

Here are five worth trying in your next project.

1. Use satisfies when you don't want to lose type information

Suppose you're building an application with different subscription plans.

type Plan = {
  price: number;
  features: string[];
};

const plans: Record<string, Plan> = {
  free: {
    price: 0,
    features: ["Basic access"],
  },
  premium: {
    price: 19,
    features: ["Unlimited access"],
  },
};

There is nothing obviously wrong with this code. It is readable, and TypeScript checks that each plan contains the required properties.

However, something interesting happens when you try this:

plans.enterprise;

TypeScript accepts it under default indexed-access checking, even though an enterprise plan doesn't exist.

By explicitly annotating the object with Record<string, Plan>, we've effectively told TypeScript that any string can be a key.

Instead, try using satisfies.

const plans = {
  free: {
    price: 0,
    features: ["Basic access"],
  },
  premium: {
    price: 19,
    features: ["Unlimited access"],
  },
} satisfies Record<string, Plan>;

Now TypeScript validates the structure of each plan while retaining knowledge of the actual keys.

plans.free;       // Valid
plans.premium;    // Valid
plans.enterprise; // TypeScript error

You also get more meaningful autocomplete suggestions in your editor.

This is particularly useful when working with configuration objects, application routes, permission mappings, theme definitions, and feature flags.

The satisfies operator was introduced in TypeScript 4.9, but it's still easy to overlook when you're accustomed to declaring types explicitly. 

TypeScript 4.9

2. Stop maintaining the same values in two places

Have you ever written something like this?

type Status = "pending" | "approved" | "rejected";

const statuses = [
  "pending",
  "approved",
  "rejected",
];

Perhaps the type is used throughout your application, while the array is used to populate a dropdown menu.

It works perfectly well until someone adds a new status to one declaration and forgets about the other.

Instead, let TypeScript derive the type directly from the array.

const statuses = [
  "pending",
  "approved",
  "rejected",
] as const;

type Status = (typeof statuses)[number];

TypeScript now understands Status as:

type Status = "pending" | "approved" | "rejected";

Need to add another status?

const statuses = [
  "pending",
  "approved",
  "rejected",
  "cancelled",
] as const;

The type updates automatically.

The as const assertion preserves the literal values rather than widening them to ordinary strings. 

Everyday Types

One source of truth instead of two independently maintained declarations.

This approach is especially handy for dropdown options, user roles, supported currencies, application events, and environment names.

It's one less thing to remember when modifying your code six months later.

3. Let TypeScript figure out your function's return type

Imagine you have a function that retrieves a user's profile.

async function getUserProfile() {
  return {
    id: 1,
    name: "Alex",
    email: "alex@example.com",
    preferences: {
      darkMode: true,
      notifications: false,
    },
  };
}

Elsewhere in your application, you need a type representing that profile.

You could manually create an interface containing all those properties. But if the function is already the authoritative source of that structure, there's another option.

type UserProfile = Awaited<
  ReturnType<typeof getUserProfile>
>;

That's it.

ReturnType extracts the function's return type, while Awaited unwraps the promise returned by the asynchronous function.

You can now use it elsewhere:

function displayProfile(profile: UserProfile) {
  console.log(profile.name);
  console.log(profile.preferences.darkMode);
}

If you later add an avatar property to the original function, the derived type includes it automatically.

This becomes particularly useful when working with database queries, service functions, custom React hooks, and data transformation utilities.

For a synchronous function, it's even simpler:

type Config = ReturnType<typeof getConfig>;

There is one important distinction, though. If you're designing a public API or a service whose return structure must remain stable, an explicit return type may be preferable. You don't necessarily want an implementation change to silently modify a public contract.

Use inference when you want types to follow the implementation. Use explicit annotations when you want the implementation to follow a contract.

4. Make impossible application states impossible to represent

This one is particularly useful for React developers, although it applies equally well to backend applications.

Consider a typical API request state.

type RequestState = {
  loading: boolean;
  data?: string[];
  error?: string;
};

Looks familiar, doesn't it?

The problem is that TypeScript also considers this perfectly valid:

const state: RequestState = {
  loading: true,
  data: ["Item 1", "Item 2"],
  error: "Something went wrong",
};

Are we loading? Did the request succeed? Did it fail?

The type allows contradictory states, leaving the rest of our application responsible for figuring out what they mean.

If our application intends loading, success, and failure to be mutually exclusive, we can express that directly.

type RequestState =
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; error: string };

Now we can write:

function render(state: RequestState) {
  switch (state.status) {
    case "loading":
      return "Loading...";

    case "success":
      return state.data.join(", ");

    case "error":
      return state.error;
  }
}

Notice that we don't need optional chaining, non-null assertions, or additional checks to determine whether data or error exists.

TypeScript already knows.

This pattern is known as a discriminated union. TypeScript uses the shared status property to determine which member of the union you're working with. 

Narrowing

Each application state carries only the information relevant to that state.

The same technique works well for payment processing, authentication, checkout workflows, background jobs, and WebSocket connections.

Instead of writing more defensive code everywhere, you improve the structure of the data itself.

5. Enable the compiler option that catches missing array elements

Take a look at this seemingly harmless piece of code.

const users = ["Alex", "Sarah", "John"];

const username = users[10];

console.log(username.toUpperCase());

In many TypeScript projects, this compiles without an error.

Run it, however, and you'll get:

TypeError: Cannot read properties of undefined

Surely TypeScript should have caught that?

By default, TypeScript doesn't necessarily account for the possibility of a missing element when accessing an array by index.

Fortunately, there is a compiler option for this.

Open your tsconfig.json and add:

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}

With this enabled, TypeScript understands that accessing an array element might return undefined. 

TypeScript

Our earlier example now produces a compile-time error.

const username = users[10];

username.toUpperCase();
// Error: 'username' is possibly 'undefined'

We are encouraged to handle the missing value appropriately.

const username = users[10];

if (username !== undefined) {
  console.log(username.toUpperCase());
}

Or, when a fallback makes sense:

const username = users[10] ?? "Guest";

The option also helps with dynamically accessed object properties.

const prices: Record<string, number> = {
  apple: 2,
  orange: 3,
};

const price = prices["banana"];

Without the option, TypeScript treats price as a number.

With it enabled, the type becomes:

number | undefined

This is particularly valuable in applications that work with dynamic data, dictionaries, cache entries, and database results.

One word of caution: enabling this in a large existing project can reveal quite a number of compiler errors. I would enable it from the beginning of a new project or introduce it gradually into an existing codebase.

A quick reference

Instead ofConsider using
Broad object type annotationssatisfies
Maintaining duplicate types and valuesas const
Manually duplicating return typesReturnType and Awaited
Multiple independent state flagsDiscriminated unions
Assuming indexed values always existnoUncheckedIndexedAccess

Final thoughts

Good TypeScript doesn't necessarily mean writing more TypeScript.

Some of the most useful improvements come from removing redundant declarations, allowing the compiler to infer information it already has, and designing types that more accurately represent the application.

You don't need to refactor your entire codebase to benefit from these techniques.

The next time you create a configuration object, define a dropdown menu, handle an API response, or access an array element, consider whether one of these approaches could make your code a little more reliable.

Small improvements tend to accumulate. And in a codebase that you'll be maintaining for years, those are often the improvements worth making.

THE CONVERSATION

Comments

Add your perspective ↓

Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.

Loading comments…

    Add your perspective

    All comments are reviewed before publication. Your name and comment will be public after approval; your email stays private and is used for account access or moderation, not a mailing list.

    Checking sign-in…