What Are the Most Common TypeScript Mistakes?

Learn What Are the Most Common TypeScript Mistakes? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Common TypeScript Mistakes

TypeScript adds static type checking to JavaScript, helping developers identify many programming errors before an application runs. However, TypeScript cannot prevent every mistake automatically. Incorrect type definitions, unsafe assertions, weak compiler settings, and misunderstandings about runtime behavior can reduce its effectiveness.

Some mistakes happen when developers treat TypeScript as JavaScript with extra annotations. Others occur when developers silence compiler errors instead of understanding why they happen. Both approaches can lead to code that compiles successfully but behaves incorrectly at runtime.

Learning these common mistakes helps you write more reliable functions, design better data models, handle external data safely, and maintain larger TypeScript applications with greater confidence.

1. Using any Too Frequently

The any type disables most type checking for a value. It can be useful during a gradual JavaScript migration, but overusing it removes many of the benefits that TypeScript provides.

Problematic example

function getDisplayName(user: any): string {
  return user.profile.displayName.toUpperCase();
}

getDisplayName({ name: "Asha" });

The parameter has no meaningful type protection. The supplied object does not contain the nested properties that the function expects, so the function can fail at runtime.

Define the expected structure instead of accepting an unrestricted value.

interface User {
  profile: {
    displayName: string;
  };
}

function getDisplayName(user: User): string {
  return user.profile.displayName.toUpperCase();
}

Now TypeScript checks that callers provide the required structure. If a value comes from an external source and its type is not yet known, use unknown and validate it before treating it as a User.

2. Using Type Assertions Without Validation

A type assertion tells TypeScript to treat a value as a specified type. It does not convert the value, check its properties at runtime, or guarantee that the value actually satisfies the asserted type.

Incorrect assumption

interface Product {
  id: number;
  name: string;
}

const product = JSON.parse(
  '{"id":"wrong","name":123}'
) as Product;

console.log(product.name.toUpperCase());

The assertion does not transform the numeric name into a string or verify that the identifier is a number. The call to toUpperCase can fail at runtime.

Treat parsed JSON as untrusted and validate its shape before using it.

interface Product {
  id: number;
  name: string;
}

function isProduct(value: unknown): value is Product {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  if (!("id" in value) || !("name" in value)) {
    return false;
  }

  return (
    typeof value.id === "number" &&
    typeof value.name === "string"
  );
}

const data: unknown = JSON.parse(
  '{"id":101,"name":"Keyboard"}'
);

if (isProduct(data)) {
  console.log(data.name.toUpperCase());
}

Use assertions only when you have a justified reason to know more about a value than the compiler can determine. When input comes from an API, a file, or browser storage, runtime validation is the safer approach.

3. Ignoring Null and Undefined

Many values in an application may be unavailable. A database lookup may return no record, an optional property may be missing, or a component may render before its data has loaded. Accessing these values without checking them can cause runtime errors.

function getUserEmail(
  email: string | undefined
): string {
  return email.toLowerCase();
}

With strict null checking enabled, TypeScript reports that email might be undefined. Resolve that possibility instead of suppressing the error.

function getUserEmail(
  email: string | undefined
): string {
  if (email === undefined) {
    return "Email not provided";
  }

  return email.toLowerCase();
}

Optional chaining and nullish coalescing can also help when they match the intended behavior. Enable strictNullChecks, which is included when strict is enabled, so the compiler can identify many unsafe null and undefined operations.

4. Adding Redundant Type Annotations

Type annotations are important, but writing an explicit type for every variable is not always necessary. TypeScript can infer many types from initial values and expressions.

// Usually unnecessary:
const courseCount: number = 12;
const courseName: string = "TypeScript";

// Type inference is sufficient:
const courseCount = 12;
const courseName = "TypeScript";

// Explicit types clarify function contracts:
function calculateAverage(
  total: number,
  count: number
): number {
  return count === 0 ? 0 : total / count;
}

The goal is not to eliminate annotations. Use inference for straightforward local values, and use explicit types where they document important contracts, clarify complex expressions, or provide a stable public API.

5. Misunderstanding Type Inference and Type Widening

TypeScript may infer a broader type than a developer expects. For example, a variable initialized with a string may be inferred as string, rather than retaining only its initial literal value.

let status = "draft";

// Inferred type: string
status = "published";
status = "anything";

type CourseStatus = "draft" | "published";

let courseStatus: CourseStatus = "draft";
courseStatus = "published";

// Compile-time error:
// courseStatus = "archived";

When a value must belong to a limited set of options, use a union of string literal types rather than an unrestricted string. For immutable values, const can preserve more specific literal information, and as const can be useful for retaining literal types in larger expressions.

6. Writing Functions Without Accurate Return Types

TypeScript can infer return types, but complex functions often benefit from clearly defined return contracts. A function that sometimes returns a value and sometimes returns nothing may not behave as callers expect.

function findCourse(
  courseId: number
): string | undefined {
  const courses = new Map([
    [1, "TypeScript Fundamentals"],
    [2, "Advanced TypeScript"]
  ]);

  return courses.get(courseId);
}

const course = findCourse(1);

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

The return type communicates that a course may not exist. Callers must account for that possibility before using the returned string. Accurate return types make functions easier to test, reuse, and maintain.

7. Forgetting to Narrow Union Types

A union type represents a value that can have one of several types. TypeScript only allows operations that are safe for the union as a whole until the code narrows the value to a more specific type.

Problematic example

function displayLength(
  value: string | string[]
): number {
  return value.length;
}

This example is valid because both strings and arrays expose a length property. The mistake would be assuming that every operation is shared by all members of a union.

Narrow the value before using type-specific operations:

function normalizeValue(
  value: string | number
): string {
  if (typeof value === "number") {
    return value.toFixed(2);
  }

  return value.trim();
}

Use checks such as typeof, instanceof, property checks, or custom type guards to narrow unions. Discriminated unions are particularly helpful when modeling objects with different states or behavior.

8. Using Generics Without a Clear Purpose

Generics provide reusable types while preserving information about the values passed into a function or component. However, adding unnecessary generic parameters can make simple code harder to understand.

// A generic is useful because the input
// and output types remain connected.
function identity(value: T): T {
  return value;
}

const numberValue = identity(42);
const textValue = identity("Hello");

// A generic is unnecessary for a function
// that only accepts one specific type.
function formatName(name: string): string {
  return name.trim();
}

Use generics when a function needs to support different types while preserving relationships between its inputs and outputs. Prefer a concrete type when the function has a single, well-defined purpose and no meaningful need for generalization.

9. Assuming TypeScript Validates API Responses

Type annotations disappear when TypeScript is compiled to JavaScript. They do not automatically verify data received from an API, JSON file, local storage, or another runtime source.

interface ApiUser {
  id: number;
  name: string;
}

async function loadUser(): Promise {
  const response = await fetch("/api/user");

  if (!response.ok) {
    throw new Error("Unable to load user");
  }

  // This annotation does not validate the JSON.
  return response.json() as Promise;
}

The assertion in this example trusts the server response without checking it. If the server returns a different shape, the application may still fail at runtime.

Treat external values as unknown and validate the required properties before returning them as ApiUser. For complex responses, runtime schema-validation libraries can help keep validation consistent and easier to maintain.

10. Misusing Optional Properties

An optional property indicates that a property may be absent. Making every property optional simply to avoid type errors weakens the model and allows incomplete objects to spread through the application.

interface CreateCourseInput {
  title: string;
  description?: string;
  durationMinutes: number;
}

const course: CreateCourseInput = {
  title: "TypeScript Basics",
  durationMinutes: 90
};

// Valid because description is optional.
// Missing title or durationMinutes is an error.

Use optional properties only when omission is valid in the real application. If different operations require different fields, define separate models for creation, updates, and responses rather than weakening a single model for every use case.

11. Ignoring Promise and Async Function Behavior

An async function always returns a Promise. Developers sometimes forget to await an asynchronous result or assume that catching an exception automatically handles every rejected Promise in their application.

async function getCourseName(): Promise {
  const response = await fetch("/api/course");

  if (!response.ok) {
    throw new Error("Unable to load course");
  }

  const data: unknown = await response.json();

  if (
    typeof data === "object" &&
    data !== null &&
    "name" in data &&
    typeof data.name === "string"
  ) {
    return data.name;
  }

  throw new Error("Invalid course response");
}

async function showCourseName(): Promise {
  try {
    const name = await getCourseName();
    console.log(name);
  } catch (error: unknown) {
    if (error instanceof Error) {
      console.error(error.message);
    }
  }
}

The example checks the response status, validates the required response field, and handles failures in the calling function. In real applications, the appropriate layer should decide whether to display an error, retry the operation, or propagate the failure to another handler.

12. Suppressing Compiler Errors Instead of Fixing Them

Type assertions, non-null assertions, and suppression comments can occasionally be necessary. However, using them to silence every compiler error hides information that could reveal a genuine defect.

interface Account {
  id: number;
  email: string;
}

function displayEmail(
  account: Account | undefined
): string {
  if (account === undefined) {
    return "Account unavailable";
  }

  return account.email;
}

Checking the value directly is safer than writing account!.email and assuming that an account always exists. Compiler diagnostics should be investigated and fixed where practical. When a suppression is genuinely needed, keep it narrow and document the reason.

13. Keeping Compiler Settings Too Permissive

TypeScript's effectiveness depends partly on its compiler settings. A project with permissive checks may allow problems that stricter settings would identify.

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

The strict option enables a collection of strict type checks, including strict null checking and stricter function typing. Apply it to new projects from the beginning when practical, or introduce it incrementally when migrating an older codebase.

Compiler settings do not replace tests, lint rules, or runtime validation. Configure them to match your framework and build tools, and ensure that type checking runs in your development workflow and continuous integration pipeline.

14. Overengineering Type Definitions

Advanced features such as mapped types, conditional types, and elaborate generic constraints can solve sophisticated problems. However, introducing them where a simple interface or union would work can make a codebase harder to understand.

type CourseStatus =
  | "draft"
  | "published"
  | "archived";

interface CourseSummary {
  id: number;
  title: string;
  status: CourseStatus;
}

Prefer the simplest type that accurately models the problem. Introduce more advanced type-level logic when it provides a clear benefit, such as eliminating repeated definitions, preserving relationships between values, or enforcing an important contract.

15. Forgetting Tests and Continuous Type Checking

A project may compile successfully while still containing runtime defects. Type checking, automated tests, linting, and build validation catch different categories of problems, so they should work together.

Add a repeatable type-check command to your package scripts:

{
  "scripts": {
    "typecheck": "tsc --noEmit"
  }
}

Run the type checker in continuous integration and keep your project's existing test and build commands. If a framework uses a separate compiler or build process, make sure the relevant checks are also executed.

Include tests for empty values, unexpected responses, invalid input, rejected asynchronous operations, and important business rules. Static types help constrain the code, while tests verify behavior under real execution conditions.

Best Practices Checklist

Use this checklist when reviewing TypeScript code or improving an existing project.

  • Enable strict type checking and understand the compiler options used by the project.
  • Prefer specific types or unknown instead of using any without a clear reason.
  • Use inference for obvious local values and annotations for important contracts.
  • Handle null and undefined explicitly.
  • Validate data received from APIs, files, and other external sources.
  • Use union types and type guards to represent and narrow alternative values.
  • Use generics when they preserve useful relationships between types.
  • Model optional properties according to actual business requirements.
  • Avoid unnecessary type assertions and compiler suppression comments.
  • Keep type checking, automated tests, and builds in continuous integration.

Conclusion

Most common TypeScript mistakes arise from weakening the type system, trusting values that have not been validated, or failing to account for the different states an application can encounter. Avoiding these mistakes requires more than memorizing syntax; it requires understanding what the compiler checks and what must still be handled at runtime.

By enabling strict checking, using accurate types, narrowing uncertain values, handling asynchronous failures, and validating external data, you can build applications that are easier to understand and maintain. Combine these practices with automated tests and regular code reviews to get the most value from TypeScript.

Code Examples

Avoid Unnecessary any

typescript
interface UserProfile {
  displayName: string;
}

interface User {
  profile: UserProfile;
}

function getDisplayName(user: User): string {
  return user.profile.displayName.toUpperCase();
}

const user: User = {
  profile: {
    displayName: "Asha"
  }
};

console.log(getDisplayName(user));
    

Specific interfaces describe the required object shape and help TypeScript catch incompatible values before execution.

Handle Missing Values

typescript
function getUserEmail(
  email: string | undefined
): string {
  if (email === undefined) {
    return "Email not provided";
  }

  return email.toLowerCase();
}

console.log(getUserEmail("USER@example.com"));
console.log(getUserEmail(undefined));
    

Explicitly handling undefined prevents unsafe property access and makes the function behavior clear for missing values.

Narrow Union Types

typescript
function normalizeValue(
  value: string | number
): string {
  if (typeof value === "number") {
    return value.toFixed(2);
  }

  return value.trim();
}

console.log(normalizeValue(42));
console.log(normalizeValue("  TypeScript  "));
    

A typeof check narrows the union to a specific type, allowing safe operations for each alternative.

Validate External Data

typescript
interface Product {
  id: number;
  name: string;
}

function isProduct(value: unknown): value is Product {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  if (!("id" in value) || !("name" in value)) {
    return false;
  }

  return (
    typeof value.id === "number" &&
    typeof value.name === "string"
  );
}

const input: unknown = {
  id: 101,
  name: "Keyboard"
};

if (isProduct(input)) {
  console.log(input.name.toUpperCase());
} else {
  console.error("Invalid product data");
}
    

A user-defined type guard validates required properties before the application treats an unknown value as a Product.

Use Literal Union Types

typescript
type CourseStatus =
  | "draft"
  | "published"
  | "archived";

function publishCourse(
  status: CourseStatus
): string {
  if (status === "published") {
    return "Course is already published";
  }

  return "Course can be published";
}

console.log(publishCourse("draft"));

// Compile-time error:
// publishCourse("deleted");
    

Literal unions restrict a variable or parameter to valid choices and help prevent unsupported values from entering the application.

Pro Tip

When TypeScript reports an error, first understand why the value does not match the expected type. Prefer correcting the model, narrowing the value, or validating external data over using any, non-null assertions, or type assertions merely to silence the compiler.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.