All posts

8 min read

JavaScript developer learning TypeScript: what carries over, what's new, 30-day plan

Practical guide for JavaScript developers transitioning to TypeScript, covering transferable concepts, new features, common pitfalls, a 30‑day learning…

What carries over

JavaScript conceptHow it works in TypeScriptWhat you need to keep in mind
Variables (let, const, var)Same syntax and block‑scoping rules.Prefer let/const; var is still allowed but discouraged.
Functions (declaration, expression, arrow)All forms are valid.You can add type annotations to parameters and return values, but the underlying call‑site behavior is unchanged.
Objects & property accessLiteral syntax ({}) and dot/bracket notation remain.You can describe the shape of an object with an interface or type.
Arrays & iterationArray, for…of, Array.prototype.map etc. work identically.Declare the element type (string[], Array<number>) to get compile‑time checks.
Modules (import / export)ES‑module syntax is identical.TypeScript adds the ability to re‑export types (export type { Foo }).
Async/await & PromisesNo change in runtime semantics.You can annotate a promise’s resolved type: Promise<User>.
DestructuringSame pattern matching for objects and arrays.You can type‑annotate the destructured variables: const { id }: { id: number } = user;.
Spread / restOperates the same on objects and arrays.Rest parameters can be typed: function sum(...nums: number[]).
Control flow (if, switch, loops)No behavioral change.TypeScript’s control‑flow analysis can narrow types inside branches.
Prototype inheritanceclass syntax and prototype chain are unchanged.TypeScript adds static typing to class members and constructors.

In short, everything you already write in JavaScript will compile as valid TypeScript as long as you don’t introduce type errors. The biggest shift is adding type information, not changing how the language works at runtime.


What's new

Side‑by‑side example

JavaScript (ES2022) – fetch a list of users and log their names.

// fetch-users.js
async function fetchUsers() {
  const response = await fetch('/api/users');
  const users = await response.json(); // assume array of objects
  users.forEach(user => console.log(user.name));
}
fetchUsers();

TypeScript – same logic, but with type safety.

// fetch-users.ts
interface User {
  id: number;
  name: string;
  email?: string; // optional property
}

async function fetchUsers(): Promise<void> {
  const response = await fetch('/api/users');
  const users: User[] = await response.json();
  users.forEach((user: User) => console.log(user.name));
}
fetchUsers();

What changed and why

  1. interface User – Declares the expected shape of each element. The compiler will flag missing id or name properties at compile time.
  2. Return type annotation (: Promise<void>) – Explicitly states that fetchUsers returns a promise that resolves to undefined. This helps callers know what to await.
  3. Variable type (users: User[]) – Guarantees that users is an array of User objects; a typo like users.forEach(u => console.log(u.nam)) will be caught.
  4. Parameter type in callback ((user: User)) – Even though TypeScript can infer the type from users, annotating it makes the intent clear and protects against future refactors.

Other new features you’ll encounter daily:

FeatureDescriptionExample
Type annotationsAdd : type after variables, parameters, return values.const count: number = 0;
Interfaces & type aliasesDefine reusable object shapes or union types.`type ID = string
EnumsEnumerated set of named constants.enum Status { Active, Inactive }
GenericsParameterize types for reusable collections.function map<T, U>(arr: T[], fn: (x: T) => U): U[] { … }
Union & intersection typesCombine or restrict possible types.`type Input = string
Literal typesRestrict a value to a specific literal.`type Direction = 'left'
Utility types (Partial, Pick, Record, etc.)Transform existing types.type PartialUser = Partial<User>;
Namespaces (rarely needed)Logical grouping of types, mostly superseded by ES modules.namespace Utils { export function … }
tsconfig.jsonCentral configuration for the compiler."strict": true, "target": "es2022"
tsc CLICompile .ts files to JavaScript.npx tsc or npx tsc -p tsconfig.json

Common pitfalls

PitfallWhy it happensHow to avoid it
Implicit anyWhen TypeScript can’t infer a type and noImplicitAny is off, the variable becomes any.Enable "noImplicitAny": true in tsconfig.json; always annotate ambiguous values.
Forgetting to install type definitionsLibraries written in plain JavaScript need @types/* packages for type info.Run npm i -D @types/<library> (e.g., npm i -D @types/lodash).
Over‑using anyTemptation to bypass the type system leads to loss of safety.Use unknown when you truly don’t know the shape, and narrow it with type guards.
Mismatched module resolutionUsing module: commonjs with ES‑style import can cause runtime errors.Keep module set to esnext or es2022 and use a bundler (esbuild, Vite, webpack) that understands ES modules.
Incorrect this typing in callbacksArrow functions preserve this, but regular functions lose the context.Either use arrow functions or explicitly type this parameter: function handler(this: HTMLElement, e: Event) { … }.
Assuming runtime type checksTypeScript types are erased at runtime; they don’t perform validation.Add runtime guards (e.g., if (typeof x !== 'string') throw …) when data comes from external sources.
Neglecting strict null checksWithout "strictNullChecks": true, null and undefined slip into any type.Turn on strict mode; handle possible null/undefined with ? or explicit checks.
Using enum when a union of literals sufficesEnums emit extra JavaScript code.Prefer `type Status = 'active'
Mixing .js and .ts files without proper allowJsThe compiler may ignore .js files, causing missing types.Set "allowJs": true if you need to compile mixed projects, but gradually migrate .js to .ts.
Relying on any from third‑party librariesSome libraries ship with any types, weakening the whole project.Contribute proper typings or use declare module with more precise types.

Your 30‑day plan

Week 1 – Foundations

  1. Set up the toolchain – npm init -y, npm i -D typescript @types/node, create a minimal tsconfig.json with "strict": true.
  2. Compile “Hello World” – Write src/index.ts with a simple console log, run npx tsc, verify the generated dist/index.js.
  3. Add basic types – Convert a small existing JS utility (e.g., a debounce function) to TS, annotating parameters and return type.
  4. Mini project – Build a CLI that reads a JSON file and prints a summary (use fs.promises.readFile). Focus on typing the file content and handling errors with try/catch.

Week 2 – Structuring code

  1. Learn interfaces & type aliases – Refactor the CLI to use an interface Config describing the JSON schema.
  2. Explore generics – Implement a reusable mapAsync<T, U>(arr: T[], fn: (x: T) => Promise<U>) helper.
  3. Introduce enum vs union literals – Replace any string‑based status flags with a union type, compare the emitted JavaScript.
  4. Mini project – Create a tiny in‑memory CRUD API using Express (install @types/express). Type request bodies and responses with interfaces.

Week 3 – Advanced type features

  1. Utility types – Use Partial, Pick, and Record to transform the CRUD models (e.g., Partial<User> for PATCH).
  2. Conditional types & inference – Write a type that extracts the element type of an array (type Elem<T> = T extends (infer U)[] ? U : never).
  3. Decorators (optional) – If you use a framework that supports them, try a simple class decorator that logs method calls.
  4. Mini project – Build a small form validator library: define a Validator<T> type, implement a few validators, and compose them.

Week 4 – Integration & best practices

  1. Linting & formatting – Add eslint with @typescript-eslint/parser and prettier. Enforce "noImplicitAny" and "strict" rules.
  2. Testing – Set up Jest with ts-jest (or Vitest). Write tests for the validator library, ensuring type errors surface during compilation.
  3. Continuous compilation – Configure tsc --watch or use Vite’s dev server to get instant feedback.
  4. Capstone project – Clone a small open‑source JavaScript repo (e.g., a todo list) and migrate it to TypeScript incrementally, committing after each module conversion. Document the migration steps and the bugs caught by the type checker.

By the end of the month you’ll have a working TypeScript codebase, a solid grasp of the type system, and a toolbox of patterns you can apply to any future project.


FAQ

How much of my existing JavaScript can I keep as‑is?

Any valid JavaScript file is also valid TypeScript; you can rename .js to .ts and the compiler will accept it, though you’ll lose type‑checking until you add annotations.

Do I need to learn a new build system?

No. The TypeScript compiler (tsc) can emit plain JavaScript that works with your current bundler (webpack, Vite, etc.). You only need to add a loader or plugin if you want on‑the‑fly transpilation.

When should I use any vs unknown?

Use any only as a last resort when you deliberately want to opt out of type checking. unknown forces you to perform a type guard before using the value, preserving safety.

Is TypeScript only for front‑end code?

No. TypeScript is equally valuable on the server (Node.js), in scripts, and even for tooling. The same type system applies regardless of the runtime environment.

Keep going

#javascript #typescript #learning #roadmap