Type Checking with TypeScript: Annotations, Inference, Objects, Arrays and Functions
Add static types to JavaScript with TypeScript: what a type checker catches, tsc and Node's type stripping, @ts-check and JSDoc, annotations and inference, function types, interfaces and object types, optional and readonly properties, collections, classes, any vs unknown.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript checks types only at run time: calling a method on undefined or passing a string where a number belongs fails when that line runs, possibly in production. A static type checker reads your code without running it and reports such mistakes as you type. Several type checkers have existed, such as Flow from Meta, but today TypeScript is the industry standard: most new projects, most popular libraries and most job listings use it. Basic annotations look almost the same in both, and the ideas carry over, so these two articles teach type checking with TypeScript.
TypeScript is JavaScript plus type annotations (and a few extra features, discussed later). The type checker, tsc, reports errors; then the annotations are removed, and what runs is plain JavaScript.

Setting up and running
npm install -D typescript # TypeScript 7: the compiler rewritten in Go, ~10x faster
npx tsc --init # create tsconfig.json
npx tsc --noEmit # type-check the whole project; exit code 1 on errors
node src/app.ts # Node strips the types and runs the file (no checking)
tsconfig.json configures the checker. The most important option is "strict": true, which enables strict null checks, no implicit any and other checks; always use it in new projects. Most editors run the checker continuously, showing errors as red underlines, along with autocompletion and refactoring powered by the types. That editor experience is a big part of TypeScript's value.
Node runs .ts files by stripping the annotations, replacing them with spaces so that line and column numbers stay the same. For example, Node's module.stripTypeScriptTypes turns function label(user: User, prefix: string = "#"): string { into function label(user , prefix = "#") {. It doesn't check anything: a file full of type errors still runs. Run tsc --noEmit in your editor, your pre-commit hook and CI (article 133).
Checking plain JavaScript
Even without converting files, TypeScript can check .js files, much like Flow lets files opt in with a // @flow comment. Add // @ts-check at the top of a file (with allowJs in the configuration), and TypeScript infers types from your code:
// @ts-check
let point = { x: 0, y: 1 };
for (point = 0; point < 3; point++) {
console.log(point);
}
point.x = 5;
/** @param {string | unknown[]} value */
function size(value) {
return value.length;
}
size(1000);
src/infer.js(3,6): error TS2322: Type 'number' is not assignable to type '{ x: number; y: number; }'.
src/infer.js(3,17): error TS2365: Operator '<' cannot be applied to types '{ x: number; y: number; }' and 'number'.
src/infer.js(3,28): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.
src/infer.js(12,6): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string | unknown[]'.
The loop accidentally reuses the variable point, and TypeScript notices that a number is being assigned to an object variable. Parameters can't be inferred from how a function uses them, so size's parameter type is declared in a JSDoc comment. JSDoc types are a gradual path into TypeScript, and some libraries use them instead of .ts files.
Annotations and inference
An annotation follows a name after a colon. The basic types are string, number, boolean, bigint, symbol, null and undefined:
let title: string = "Report";
let count = 3; // inferred: number
count = "three";
function area(width: number, height: number): number {
return width * height;
}
area(2, "3");
area(2);
src/basics.ts(3,1): error TS2322: Type 'string' is not assignable to type 'number'.
src/basics.ts(8,9): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
src/basics.ts(9,1): error TS2554: Expected 2 arguments, but got 1.
TypeScript infers types from initial values and return statements, so you rarely annotate local variables: count is a number because it starts as one. Annotate function parameters (they can't be inferred) and usually the return types of exported functions, which documents the contract and catches a wrong return early. Note that JavaScript would have happily computed 2 * "3" as 6 and area(2) as NaN.
Function types
function greet(name: string, greeting = "Hello", punctuation?: string): string {
return `${greeting}, ${name}${punctuation ?? "!"}`;
}
type Comparator = (a: number, b: number) => number; // a function type
const byValue: Comparator = (a, b) => a - b; // a and b inferred as number
function sum(...values: number[]): number { // rest parameter
return values.reduce((total, v) => total + v, 0);
}
?makes a parameter optional; its type inside the function includesundefined. A parameter with a default value is optional automatically, and its type is inferred from the default.- Function types are written like arrow functions:
(a: number, b: number) => number. Callbacks passed to typed functions get their parameter types from context, as inbyValue. - A function that returns nothing has return type
void; anasyncfunction returnsPromise<T>.
Object types
Describe the shape of an object with a type alias or an interface:
type Point = { x: number; y: number };
interface User {
readonly id: number;
name: string;
email?: string; // optional
}
const ada: User = { id: 1, name: "Ada" };
ada.id = 2;
const lin: User = { id: 2, nme: "Lin" };
function describe(user: User): string {
return user.email.toLowerCase();
}
src/objects.ts(10,5): error TS2540: Cannot assign to 'id' because it is a read-only property.
src/objects.ts(11,28): error TS2561: Object literal may only specify known properties, but 'nme' does not exist in type 'User'. Did you mean to write 'name'?
src/objects.ts(14,10): error TS18048: 'user.email' is possibly 'undefined'.
- Optional properties (
email?) may be missing. Withstrict, TypeScript makes you handle that case:user.email?.toLowerCase()or a check first. This single feature prevents the most common JavaScript runtime error, reading a property ofundefined. readonlyproperties can't be reassigned. It's a compile-time check only; useObject.freeze(article 102) for run-time immutability.- A misspelled property in an object literal is caught, with a suggestion.
- Interfaces and type aliases are mostly interchangeable for object shapes. Interfaces can be extended (
interface Admin extends User { role: string }) and merged; type aliases can also name unions and other types (next article). Pick one style per codebase.
TypeScript's typing is structural: any object with the right properties matches, whatever created it. You don't declare that an object "is a" Point; it just has to look like one.
Arrays, tuples, maps and sets
const scores: number[] = [90, 85]; // or Array<number>
scores.push("100"); // error: string is not a number
const pair: [string, number] = ["age", 36]; // a tuple: fixed length and types
const ages: Record<string, number> = { ada: 36 };
const tags = new Set<string>(["a"]);
tags.add(1); // error: number is not a string
const cache = new Map<string, User>();
const ready: Promise<boolean> = Promise.resolve(true);
Types in angle brackets are type arguments: Set<string> is a set of strings, Map<string, User> maps strings to users, and Promise<boolean> resolves to a boolean. These are generic types; the next article shows how to write your own. readonly number[] describes an array that the code must not modify.
Classes
interface Shape {
area(): number;
}
class Circle implements Shape {
#secret = 42; // JavaScript private field
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Square implements Shape {
side = 2;
}
src/classes.ts(16,7): error TS2420: Class 'Square' incorrectly implements interface 'Shape'.
Property 'area' is missing in type 'Square' but required in type 'Shape'.
Class fields are declared with types; implements checks that a class provides everything an interface requires. A class name is also a type (let c: Circle). TypeScript has its own private keyword, but it's only checked at compile time. JavaScript's #private fields (article 71) are enforced at run time, so prefer them.
any and unknown
anyturns type checking off for a value: every operation is allowed. It's an escape hatch for migration, and it spreads silently, so avoid it.strictreports implicitany, such as an unannotated parameter.unknownis the safe alternative for values whose type you don't know yet, such as the result ofJSON.parseor a caught error. You can't use anunknownvalue until you've narrowed it with checks:
function parseConfig(text: string) {
const data: unknown = JSON.parse(text);
data.port; // error TS18046: 'data' is of type 'unknown'
if (typeof data === "object" && data !== null && "port" in data && typeof data.port === "number") {
return data.port; // narrowed: number
}
return 3000;
}
Types vanish at run time
The annotations are erased before the code runs, so nothing checks types while the program runs. A function annotated to return a User returns whatever JSON.parse produced, whatever the type says. Data that comes from outside your program (HTTP requests, files, localStorage, environment variables) must still be validated at run time:
// In TypeScript this would be: function parseUser(json: string): User
// The annotation promises a User, but after type stripping nothing checks
// the data at run time. Values from outside (JSON, forms, APIs) need real checks.
function parseUser(json) {
const data = JSON.parse(json);
const problems = [];
if (typeof data !== "object" || data === null) return { ok: false, problems: ["not an object"] };
if (!Number.isInteger(data.id)) problems.push("id must be an integer");
if (typeof data.name !== "string" || data.name === "") problems.push("name must be a non-empty string");
if ("email" in data && typeof data.email !== "string") problems.push("email must be a string");
return problems.length ? { ok: false, problems } : { ok: true, user: data };
}
console.log(parseUser('{"id": 1, "name": "Ada"}'));
console.log(parseUser('{"id": "1", "name": ""}'));
console.log(parseUser('{"id": 2, "name": "Lin", "email": 42}'));
console.log(parseUser("null"));
{ ok: true, user: { id: 1, name: 'Ada' } }
{
ok: false,
problems: [ 'id must be an integer', 'name must be a non-empty string' ]
}
{ ok: false, problems: [ 'email must be a string' ] }
{ ok: false, problems: [ 'not an object' ] }
Libraries such as Zod, Valibot and ArkType let you write such a validation schema once and derive the TypeScript type from it, so the checks and the types can't drift apart.
Common questions
Flow or TypeScript?
TypeScript. Flow is still used inside Meta, but TypeScript has won the wider ecosystem: editor support, library type definitions, jobs and tooling. The concepts transfer directly between the two.
Does TypeScript make my code slower or bigger?
No. Types are erased, so the JavaScript that runs is the same as if you'd written it without them. The only cost is at build time.
Should I annotate every variable?
No. Let inference do its job for local variables. Annotate function parameters, exported functions' return types, and anything inference gets too wide or too narrow.
Summary
- TypeScript adds type annotations to JavaScript;
tsc --noEmitand editors check them, and Node, esbuild ortscstrip them before running. Use"strict": true. // @ts-checkplus JSDoc comments brings checking to plain.jsfiles.- Annotate parameters and exported return types, and let inference handle the rest. Function types look like arrow functions;
?marks optional parameters and properties. - Interfaces and type aliases describe object shapes, structurally;
readonlyand optional properties are checked, andstrictforces you to handleundefined. - Arrays (
T[]), tuples,Set<T>,Map<K, V>,Promise<T>andRecord<K, V>are typed collections. Classes declare typed fields and canimplementinterfaces. - Prefer
unknownoverany, and validate outside data at run time, because types are erased.
Practice Questions
Which line or lines does TypeScript reject with strict enabled, and why?
interface Product { name: string; price: number; discount?: number }
const p: Product = { name: "Pen", price: 2 };
const final = p.price - p.discount;
const label = p.name.toUpperCase();
Answer
The third line: p.discount is optional, so its type is number | undefined, and subtracting a possibly undefined value is an error (it would produce NaN at run time). Fix it with a default: p.price - (p.discount ?? 0).
Why does node app.ts run a file that tsc --noEmit reports errors in?
Answer
Node only strips the type annotations and runs the remaining JavaScript; it never type-checks. Checking is a separate step, done by tsc or your editor, which you should also run in CI.
Write a function type Validator for functions that take a string and return either null (valid) or an error message, and a value notEmpty of that type.
Answer
type Validator = (value: string) => string | null;
const notEmpty: Validator = (value) =>
value.trim() === "" ? "This field is required" : null;
value gets its type from Validator, so it needs no annotation.
Previous: JSX: Markup Expressions in JavaScript, and What They Compile To
Next: TypeScript Beyond the Basics: Unions, Narrowing, Generics and Discriminated Unions

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.