Skip to content
jshacks.dev
TypeScript

TypeScript Mistakes Beginners Make

Eight TypeScript 6 mistakes beginners make, from overusing any to trusting as assertions, each with the failing code, the compiler message and the fix.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, npm, Node.js and JavaScript logos.

Most TypeScript mistakes are not syntax errors. They are habits carried over from JavaScript, or shortcuts that silence the compiler without fixing the problem, and they show up weeks later as runtime errors the types were supposed to prevent. This post lists eight we see most often in code reviews, each with the failing code, what the compiler says on TypeScript 6.x, and the fix. The advice is the same on the native TypeScript 7 compiler. Every entry names the fix, since a list of mistakes without one is only criticism.

1. Reaching for any

any turns off checking for a value and everything it touches. It is the quickest way to make an error disappear, and the most expensive.

any.tsTypeScript
function parse(json: string): any {
  return JSON.parse(json);
}

const user = parse('{"name":"Ada"}');
console.log(user.nmae.toUpperCase());
Text
TypeError: Cannot read properties of undefined (reading 'toUpperCase')

The typo nmae compiled, because user is any. Use unknown for values whose shape you do not know, which forces a check before use, or describe the shape and validate it.

unknown.tsTypeScript
interface User {
  name: string;
}

function isUser(value: unknown): value is User {
  return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string";
}

const data: unknown = JSON.parse('{"name":"Ada"}');
if (isUser(data)) {
  console.log(data.name.toUpperCase());
}
Text
ADA

Turn on noImplicitAny, which is part of strict, so a missing annotation is an error rather than a silent any.

2. Silencing errors with as

An as assertion tells the compiler to believe you. When the claim is wrong, nothing warns you.

assertion.tsTypeScript
interface Order {
  id: number;
  total: number;
}

const order = { id: 1 } as Order;
console.log(order.total.toFixed(2));
Text
TypeError: Cannot read properties of undefined (reading 'toFixed')

The fix is to make the value honest: build a complete object, validate input from outside, or use satisfies when you only want a check. Keep as for cases such as a DOM lookup, where you know something the compiler cannot, and write a comment saying why.

3. Turning strict mode off

Many beginners copy a tsconfig.json with "strict": false or leave it out. Without strictNullChecks, every type silently includes null and undefined, which means the compiler will not warn about the most common JavaScript error.

nulls.tsTypeScript
function firstChar(text: string | undefined): string {
  return text.charAt(0);
}
Text
nulls.ts(2,10): error TS18048: 'text' is possibly 'undefined'.

This message appears only with strictNullChecks on. Without it, the code compiles and fails at runtime when text is missing. Start new projects with "strict": true. For an existing codebase, enable the family of flags one at a time and fix the errors each reveals.

4. Declaring types that duplicate each other

Writing the same shape twice, once as an interface and once as a hand-copied variant, guarantees they will drift.

duplicate.tsTypeScript
interface User {
  id: number;
  name: string;
  email: string;
}

interface UserUpdate {
  name?: string;
  email?: string;
}

Adding a phone field to User leaves UserUpdate stale and no error appears. Derive the second type from the first.

derived.tsTypeScript
interface User {
  id: number;
  name: string;
  email: string;
}

type UserUpdate = Partial<Omit<User, "id">>;

const update: UserUpdate = { email: "[email protected]" };
console.log(update);
Text
{ email: '[email protected]' }

5. Using enums where a union would do

Numeric enums accept any number, and every enum emits runtime code. For a fixed set of string values, a union of literals is lighter and safer.

enums.tsTypeScript
enum Level {
  Low,
  High,
}

const level: Level = 42;
console.log(level);
Text
42

In older versions of TypeScript this compiled with no error, and the 42 flowed through the program. Since TypeScript 5.0, assigning an out-of-range literal to an enum is an error, but any non-literal number expression is still accepted by numeric enums. A string-literal union gives you the same names with none of those holes.

union.tsTypeScript
type Level = "low" | "high";

function setLevel(level: Level): string {
  return `level is ${level}`;
}

console.log(setLevel("high"));
Text
level is high

6. Forgetting that types disappear

Types are erased at compile time, so they cannot validate data that arrives at runtime. A beginner declares a type for an API response and assumes the server obeys it.

runtime.tsTypeScript
interface Product {
  id: number;
  price: number;
}

async function loadProduct(): Promise<Product> {
  const response = await fetch("https://api.example.com/products/1");
  return response.json();
}

If the server returns price as a string, the types say number and the code does arithmetic on a string. Validate at the boundary with a schema library or a hand-written guard, and let the validated type flow inward. The compiler checks your code against your declarations, not your declarations against reality.

7. Mutating arrays and objects that should be readonly

A function that takes an array and sorts it in place changes the caller's data. TypeScript lets this through unless you ask it not to.

mutate.tsTypeScript
function sortedNames(names: string[]): string[] {
  return names.sort();
}

const original = ["Grace", "Ada"];
const result = sortedNames(original);
console.log(original, result);
Text
[ 'Ada', 'Grace' ] [ 'Ada', 'Grace' ]

sort mutated original. Mark parameters you do not change as readonly string[], and the compiler reports the mutation.

readonly.tsTypeScript
function sortedNames(names: readonly string[]): string[] {
  return [...names].sort();
}

const original = ["Grace", "Ada"];
console.log(sortedNames(original), original);
Text
[ 'Ada', 'Grace' ] [ 'Grace', 'Ada' ]

With readonly string[], calling names.sort() directly is error TS2339, since sort is not on readonly string[], which nudges you to copy first. For an in-place alternative, toSorted exists on ES2023 and later targets.

8. Fighting inference

Beginners often annotate everything, including variables the compiler already understands. The result is noise, and sometimes a worse type.

inference.tsTypeScript
const count: number = 3;
const names: string[] = ["a", "b"];
const doubled: number[] = names.map((name): number => name.length * 2);

const count = 3 is inferred as the literal 3, which is more precise than number. The annotated version widens it. Annotate function parameters, exported return types and empty initializers, and let inference handle the rest.

A way to learn from the compiler

The compiler's messages are teachers, if you read them in order. Treat the first error in a file as the real one, since later errors are often consequences of it. Hover over the types in your editor to see what was inferred. When you feel the urge to add any or as, stop and ask what the compiler knows that you do not, or what you know that you have not told it. One of those is the bug.

A habit worth building early is to run the type checker in your editor and in continuous integration with the same configuration. A beginner who sees a green editor and a red build learns that types are optional, which is the wrong lesson.

Why these mistakes persist

Each of these mistakes is a reasonable response to friction. The compiler reports an error, the deadline is close, and any or as makes the red line go away in one keystroke. The trouble is that the error was a true statement about the code, and the code is now wrong in a way nobody can see. Learning TypeScript is mostly learning to treat that red line as information instead of an obstacle.

A useful exercise is to take a file full of assertions and remove them one at a time, then read what the compiler says. Often the message points at a real gap: a function that can return undefined, an object that is missing a field in one branch, a union that was never narrowed. Fixing the gap removes the assertion and the bug together. Sometimes the compiler is wrong or the type is too strict, and then the honest fix is to improve the type, not to bypass it.

Code review questions that catch them

Reviewers can look for these mistakes without running anything. Ask of every any, what is its real type, and can it be unknown? Ask of every as, what check would make this unnecessary? Ask of every !, under what condition is the value missing, and what should happen then? Ask of every @ts-ignore, can it be @ts-expect-error with a reason? Ask of every new interface, does it duplicate an existing one that it could be derived from?

Asking the same five questions every time is more effective than a long style guide, because the questions point at the underlying habit. Teams that adopt them tend to find that the number of assertions drops without any rule forbidding them, since the author starts answering the questions before the reviewer asks.

What good looks like

A healthy TypeScript codebase has strict mode on, few assertions with a comment on each, validation at every boundary where data enters, and types that are derived from a small number of source definitions. Its error messages are short because its types are simple. Newcomers can read it, because each type says what the code means and nothing more. That is the target to learn toward, and each fix in this post moves a codebase a step closer to it.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.