Coding Tricks

TypeScript Tips for Beginners: Types That Catch Bugs

We ran a two-line JavaScript function through Node: addTax("100", 0.2). It printed 10020. No error, no warning, just a wrong price. TypeScript exists to stop exactly that kind of bug before the code runs. These TypeScript tips for beginners focus on the types that catch real mistakes, and every example below was compiled with TypeScript 7.0.2 on our machine, with the exact error messages copied from the terminal.

One honest note before we start: these are compiler checks we actually ran, on Node v24.22.1 and Windows 10, on November 16, 2026. They aren’t benchmarks of a big codebase. The scripts and full output sit in our test folder, and you can paste any snippet into your own project to check it.

Quick answer: Type your function parameters, let TypeScript infer the rest, treat “possibly undefined” errors as free bug reports, use unknown instead of any, and replace loose strings with literal unions like "draft" | "published". Most important: run tsc. Node can run .ts files but never checks the types.

  • Since TypeScript 6.0, strict is on by default. TypeScript 7 kept it, and our tests confirmed it.
  • noUncheckedIndexedAccess isn’t part of strict. Turn it on yourself.
  • any switches the checker off. Our bad-JSON example compiled cleanly and then crashed.
  • Node 24 ran a file with a type error and printed a wrong answer.

Setup in two minutes

TypeScript 7.0 came out on July 8, 2026. It’s a port of the compiler to Go, and Microsoft’s announcement says full builds typically run 8x to 12x faster than before. For you as a beginner, nothing about the language changes. Install it per project:

npm install -D typescript
npx tsc --version        # we got: Version 7.0.2
npx tsc --noEmit app.ts  # check types without writing .js files

The big change for beginners arrived one version earlier. The TypeScript 6.0 release notes made strict true by default. Older tutorials tell you to “turn on strict mode first.” You don’t have to anymore. We checked: our first example below threw two errors by default, and zero with --strict false.

TypeScript tips for beginners: bugs caught by tsc vs what Node printed

1. Always run tsc (Node won’t check types)

Node 24 can run a .ts file directly. That’s handy, and it fools a lot of beginners. The Node.js TypeScript docs are blunt about it: Node replaces the TypeScript syntax with whitespace, “and no type checking is performed.”

function double(n: number): number {
  return n * 2;
}
const wrong: number = double("5");
console.log(wrong);

tsc refused it: error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node ran it without complaint and printed 10, because JavaScript quietly turned “5” into a number. The types only protect you if something reads them. Add tsc --noEmit to your test script or editor and run it before you run the code.

2. Type every function parameter

Here’s the addTax bug from the intro. Without types, TypeScript in strict mode won’t even accept the function:

function addTax(price, rate) {
  return price + price * rate;
}
// error TS7006: Parameter 'price' implicitly has an 'any' type.

Add price: number, rate: number and the call addTax("100", 0.2) fails with TS2345 instead of printing 10020. That’s the whole value of TypeScript in one line.

The flip side: don’t annotate everything. const total = 0 is already a number. TypeScript’s Everyday Types handbook page suggests letting inference work and writing types where data enters your code: parameters, return values of exported functions, and anything from outside.

3. Love the “possibly undefined” error

Beginners hate this one. They shouldn’t. Array.find returns undefined when nothing matches, and TypeScript makes you deal with it:

const user = users.find(u => u.id === 3);
console.log(user.name.toUpperCase());
// error TS18048: 'user' is possibly 'undefined'.

console.log(user?.name.toUpperCase() ?? "No user with id 3");  // fixed

We ran the unfixed version with Node anyway. It crashed: TypeError: Cannot read properties of undefined (reading 'name'). The fixed one printed “No user with id 3”. Every “possibly undefined” error is a crash that hasn’t happened yet. Fix it with optional chaining (?.), a default (??), or an if check, which the handbook calls narrowing.

4. Use literal unions instead of plain strings

If a value can only be one of a few words, say so:

type Status = "draft" | "published" | "archived";
function setStatus(s: Status) { return s; }

setStatus("publshed");
// error TS2345: Argument of type '"publshed"' is not assignable to parameter of type 'Status'.

With s: string, that typo would sail through and break a filter somewhere else. As a bonus, your editor now autocompletes the three valid values.

5. Make switch statements exhaustive

Give each object shape a kind field, then add a never check at the end of the switch. If someone adds a new shape and forgets to handle it, the build fails:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "triangle"; base: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "square": return shape.size ** 2;
    default: {
      const unhandled: never = shape;  // triangle lands here
      return unhandled;
    }
  }
}
// error TS2322: Type '{ kind: "triangle"; ... }' is not assignable to type 'never'.

The error even names the case you missed. On a team, this tip alone stops a whole class of “we added a new option and half the app ignored it” bugs.

6. Use unknown, not any

any means “stop checking.” unknown means “check before use.” Strict mode already makes caught errors unknown (the useUnknownInCatchVariables option), which is why this fails:

try {
  JSON.parse("{bad json");
} catch (err) {
  console.log(err.message);  // error TS18046: 'err' is of type 'unknown'.
}

// fixed, inside the catch block:
console.log(err instanceof Error ? err.message : String(err));

JavaScript lets you throw anything, including a string or a number, so the check isn’t paranoia. Our fixed version printed Node’s real parse error message.

7. Check JSON where it enters your code

This is the bug TypeScript can’t catch on its own. JSON.parse returns any, and any can be assigned to anything:

type User = { name: string; age: number };
const raw = JSON.parse('{"name": "Ana", "agee": 30}');  // typo in the data
const u: User = raw;
console.log(u.age.toFixed(0));

tsc: zero errors. Node: TypeError: Cannot read properties of undefined (reading 'toFixed'). The type said age exists, and the data disagreed. The fix is a small type guard that checks the shape at runtime:

function isUser(x: unknown): x is User {
  return typeof x === "object" && x !== null &&
    typeof (x as User).name === "string" &&
    typeof (x as User).age === "number";
}

const raw: unknown = JSON.parse(text);
if (isUser(raw)) console.log(raw.age.toFixed(0));
else console.log("Bad user data:", raw);

This one compiled cleanly and printed “Bad user data” instead of crashing. API responses, localStorage, form input and files all deserve the same treatment. The same lesson shows up with fetch in our list of JavaScript async/await mistakes.

8. Turn on noUncheckedIndexedAccess

Strict mode doesn’t cover everything. Reading items[2] from a two-item array, or a missing key from a Record, passed with zero errors under default settings. With the flag on, both were caught:

const scores: Record<string, number> = { ana: 91 };
const benScore = scores["ben"];
console.log(benScore.toFixed(1));

const items = ["a", "b"];
const third = items[2];
console.log(third.toUpperCase());

// npx tsc --noEmit --noUncheckedIndexedAccess scores.ts
// error TS18048: 'benScore' is possibly 'undefined'.
// error TS18048: 'third' is possibly 'undefined'.

The tsconfig reference explains that the option adds undefined to any undeclared field. It’s noisier, so new projects are the best place to switch it on. Add "noUncheckedIndexedAccess": true to compilerOptions.

9. Let TypeScript catch option typos

Pass an object literal with a property the type doesn’t have, and TypeScript stops you. It even guesses what you meant:

type Options = { retries?: number; timeoutMs?: number };
request("/api", { retries: 3, timeout: 500 });
// error TS2561: ... 'timeout' does not exist in type 'Options'.
//   Did you mean to write 'timeoutMs'?

In plain JavaScript, timeout: 500 would be silently ignored and your request would use the default. So write option types for your functions, even small ones.

10. Use satisfies and readonly for config

The satisfies operator, added in TypeScript 4.9, checks an object against a type without widening it. In our test, auth: "yes" in a route table typed as Record<string, Route> was flagged with TS2322. Pair it with as const and readonly for values that should never change:

const COLORS = ["red", "green"] as const;
COLORS.push("blue");
// error TS2339: Property 'push' does not exist on type 'readonly ["red", "green"]'.

type Config = { readonly apiUrl: string };
config.apiUrl = "http://localhost";
// error TS2540: Cannot assign to 'apiUrl' because it is a read-only property.

11. Reach for generics before any[]

A helper typed with any[] loses all information. A generic keeps it. Calling .toUpperCase() on the first item of [10, 20] passed with the any version and failed with the generic one, with two errors: the value might be undefined, and toUpperCase doesn’t exist on number.

function first<T>(list: T[]): T | undefined { return list[0]; }

That’s all a beginner needs from generics at first, a type parameter that carries through. The Generics handbook page goes further when you’re ready.

The thing tip lists don’t tell you: TypeScript’s guarantees end at any and at the edges of your program. Our JSON example compiled with zero errors and still crashed, and Node happily ran a file that tsc rejected. So a green build doesn’t mean “no type bugs.” It means “no type bugs in the parts you described honestly.” Search your code for any and as casts now and then. That’s where the remaining bugs hide.

Common errors and fixes

  • TS5112: “tsconfig.json is present but will not be loaded if files are specified on commandline.” We hit this one ourselves. TypeScript 7 refused tsc file.ts in a folder that had a tsconfig. Run plain npx tsc to use the config, or add --ignoreConfig to check one file.
  • TS7006, implicit any. Add a type to the parameter. Don’t silence it with : any.
  • TS18048, possibly undefined. Narrow it with ?., ?? or an if. Avoid the ! non-null assertion unless you’re truly sure.
  • “Cannot find name ‘process'”. TypeScript 6.0 changed the default types to an empty list, per its release notes. Install @types/node and add "types": ["node"] to tsconfig.

Are these TypeScript tips for beginners enough?

For your first few months, yes. If you only adopt three, pick these: run tsc in your workflow, type your parameters, and replace any with unknown plus a check. Those three caught most of the bugs in our tests. Skip advanced tricks like conditional and mapped types until you’re comfortable reading the errors above.

TypeScript unknown vs any: a type guard that checks JSON before use

Still shaky on the JavaScript underneath? TypeScript is JavaScript with types, so our tested JavaScript one-liners are a good warm-up. And if Python is your other language, our Python tricks for beginners uses the same run-every-snippet approach.

Next: once your types compile, the bugs that remain are mostly async ones. Read our ten async/await mistakes before your first API project.

FAQ

Should I learn TypeScript or JavaScript first?

Learn basic JavaScript first: variables, functions, arrays, objects and promises. TypeScript adds types on top and doesn’t change how the code runs, so every JavaScript skill carries over directly.

Is strict mode on by default in TypeScript?

Yes, since TypeScript 6.0. Our tests on TypeScript 7.0.2 confirmed it: the implicit-any error appeared with no config, and disappeared only with --strict false.

Can Node.js run TypeScript files directly?

Yes. Type stripping has been on by default since Node v22.18.0 and v23.6.0, but it removes types without checking them. Some features, such as enums, aren’t supported by type stripping. Use tsc to find type errors.

How long does it take to learn TypeScript?

If you already write JavaScript, the basics in this article take a few days of practice. Generics and advanced types take longer, but you can ship useful code without them.

Leave a Comment