TypeScript types, inference, any, unknown and never
This is the first stop in the TypeScript basics path. It covers how TypeScript attaches a type to every value: by an annotation you write, or by inference from the code. It then covers the three special types that every beginner meets early (any, unknown and never) and the two ways to type a list of values (arrays and tuples). Every sample is part of one small script for an invented online shop, OrdersPortal.
What you’ll build
Section titled “What you’ll build”By the end you will have a script that summarizes a day’s orders: it reads order data that arrives as untyped JSON, checks it before trusting it, totals the orders, and reports the best-selling product as a [sku, quantity] pair. Along the way you will see the compiler errors beginners hit most often and what each one is telling you.
Prerequisites
Section titled “Prerequisites”- Node.js 22.18 or later (the samples were run with Node.js 22) and npm.
- Basic JavaScript: variables, functions, arrays and objects. If you need a refresher, start with the JavaScript basics.
- A folder with TypeScript installed. The samples were compiled with TypeScript 7.0.2:
mkdir orders-basics && cd orders-basicsnpm init -ynpm pkg set type=modulenpm install -D typescriptSave each sample as orders.ts, then type-check and compile it with npx tsc --module nodenext orders.ts and run the result with node orders.js. The --module nodenext flag tells TypeScript to follow Node.js’s module rules, so with "type": "module" each file is its own ES module. Without a tsconfig.json, TypeScript 7 uses its defaults for everything else, which include strict mode. When a sample shows an error, tsc prints it with the file name and position, for example orders.ts(2,5): error TS2322: ...; this page shows the same messages. The Modules and compilation tutorial replaces this command with a project configuration.
Type annotations
Section titled “Type annotations”A type annotation is a colon and a type after a name: let quantity: number = 2;. You can annotate variables, function parameters and function return types. The basic types match JavaScript’s values: string, number (integers and decimals alike), boolean, bigint, symbol, null and undefined. Object shapes are written in braces, { id: string; total: number }, and the objects tutorial gives them names.
The compiler then checks every use. Assigning a string to a number variable, passing the wrong argument type, or returning the wrong type from a function is a compile error, reported before the code runs. Annotations exist only for the compiler: tsc removes them, and the JavaScript it writes is the same code without types.
A union type, written with |, allows several types: string | null means “a string, or null”. Unions are covered in depth in the core type system hub; for now, read | as “or”.
let orderId: string = "ORD-1042";let quantity: number = 2;let isGift: boolean = false;let couponCode: string | null = null;
function lineTotal(unitPrice: number, qty: number): number { return unitPrice * qty;}
const customer: { name: string; email: string } = { name: "Ada Lopez", email: "ada@example.test",};
couponCode = "WELCOME10";console.log(`${orderId} for ${customer.name}: ${lineTotal(19.95, quantity)} EUR, gift=${isGift}, coupon=${couponCode}`);Output:
ORD-1042 for Ada Lopez: 39.9 EUR, gift=false, coupon=WELCOME10Changing the second line to let quantity: number = "2"; fails with error TS2322: Type 'string' is not assignable to type 'number'.
Pitfalls:
- Use the lower-case types.
stringandnumberare the primitive types;StringandNumberare wrapper object types you almost never want. - Annotations are not conversions.
const qty: number = Number(input)converts; an annotation alone never changes a value at run time.
Type inference
Section titled “Type inference”You do not need to annotate everything. When a variable has an initializer, TypeScript infers its type from the value: let quantity = 2 is a number, and assigning "two" later is still an error. Function return types are inferred from the return statements, array types from their elements, and type arguments of generic functions from their arguments.
Inference depends on whether the variable can change. let status = "paid" is inferred as string, because the variable could later hold any string. const status = "paid" is inferred as the literal type "paid", because it can never change. That difference matters when a function accepts only certain strings.
A good rule: annotate function parameters (they cannot be inferred), annotate the return types of exported functions (they are a contract with callers, and the annotation catches accidental changes), and let inference handle local variables. Hovering over a name in an editor such as Visual Studio Code shows the inferred type.
let quantity = 2; // numberconst orderStatus = "paid"; // the literal type "paid"let label = "paid"; // string
const prices = [19.95, 5, 12.5]; // number[]const mixed = ["SKU-RED-01", 2]; // (string | number)[]
function orderTotal(values: number[]) { return values.reduce((sum, v) => sum + v, 0); // return type inferred as number}
function setStatus(next: "pending" | "paid" | "shipped"): string { return `status -> ${next}`;}
quantity += 1;console.log(quantity, orderTotal(prices), mixed.length);console.log(setStatus(orderStatus));console.log(setStatus(label as "paid")); // label is string, so it needs a cast hereOutput:
3 37.45 2status -> paidstatus -> paidPassing label without the cast fails with error TS2345: Argument of type 'string' is not assignable to parameter of type '"paid" | "pending" | "shipped"'. The better fix is to declare label with const or annotate it with the union; a cast (as) tells the compiler to trust you, and is explained in Type narrowing.
Pitfalls:
- Empty arrays take whatever you push.
const skus = []has no element type yet; it becomesstring[]afterskus.push("SKU-1"), and(string | number)[]if a number is pushed later. Writeconst skus: string[] = []so a wrong push is an error. - Inference is not guessing. If the inferred type is wider than you want, annotate; do not work around it with casts.
Any unknown and never
Section titled “Any unknown and never”Three types do not describe ordinary values. any switches type checking off: anything can be assigned to it and anything can be done with it, so mistakes pass silently. unknown (TypeScript 3.0) also accepts any value, but you must check what it is before using it; it is the safe type for data from outside your program, such as parsed JSON. never is the type with no values: the return type of a function that always throws, and the type left over when every case has been handled.
Under strict mode, the compiler refuses to give a parameter an implicit any, so any appears only where someone writes it. Treat each explicit any as a hole in the type system and prefer unknown plus a check. Narrowing a value with typeof, in and similar checks is covered in Type narrowing.
First, what any allows:
const loose: any = JSON.parse('{"id":"ORD-1","total":"40"}');console.log(loose.total.toFixed(2)); // compiles, but total is a stringThis compiles without complaint and then throws TypeError: loose.total.toFixed is not a function at run time, because total arrived as a string. The same data handled as unknown, with a check before use:
interface OrderInput { id: string; total: number;}
function fail(message: string): never { throw new Error(message);}
function parseOrder(json: string): OrderInput { const data: unknown = JSON.parse(json); if (typeof data === "object" && data !== null && "id" in data && "total" in data) { if (typeof data.id === "string" && typeof data.total === "number") { return { id: data.id, total: data.total }; } } return fail(`Invalid order: ${json}`);}
for (const json of ['{"id":"ORD-1","total":40}', '{"id":"ORD-2","total":"40"}']) { try { const order = parseOrder(json); console.log(`${order.id}: ${order.total.toFixed(2)}`); } catch (error) { console.log(error instanceof Error ? error.message : "unknown error"); }}Output:
ORD-1: 40.00Invalid order: {"id":"ORD-2","total":"40"}Using unknown without a check, const data: unknown = JSON.parse(json); data.total;, fails with error TS18046: 'data' is of type 'unknown'.
Pitfalls:
anyspreads. A value read from ananyis alsoany, so oneanycan switch off checking far from where it was written.JSON.parsereturnsany. Assign its result tounknown(as above) so the compiler makes you check it.
Arrays and tuples
Section titled “Arrays and tuples”An array type is written number[] or, equivalently, Array<number>: any number of elements, all of that type. Methods are typed too: map on a number[] gives you numbers in the callback, and find returns number | undefined, because nothing may match. readonly number[] removes the methods that change the array, such as push and sort.
A tuple is an array with a fixed number of positions, each with its own type: [string, number] is exactly a string followed by a number. Tuples suit small, positional results such as a [sku, quantity] pair, and they destructure naturally: const [sku, qty] = best;. Elements can be labeled for readability: [sku: string, quantity: number]. More tuple features, such as optional and rest elements, are in the core type system hub.
type SkuCount = [sku: string, quantity: number];
const lines: { sku: string; quantity: number }[] = [ { sku: "SKU-RED-01", quantity: 2 }, { sku: "SKU-BLU-02", quantity: 5 }, { sku: "SKU-RED-01", quantity: 4 },];
function bestSeller(items: readonly { sku: string; quantity: number }[]): SkuCount | undefined { const counts = new Map<string, number>(); for (const { sku, quantity } of items) { counts.set(sku, (counts.get(sku) ?? 0) + quantity); } let best: SkuCount | undefined; for (const [sku, quantity] of counts) { if (best === undefined || quantity > best[1]) best = [sku, quantity]; } return best;}
const skus: string[] = lines.map((l) => l.sku);const result = bestSeller(lines);if (result) { const [sku, quantity] = result; console.log(`${skus.length} lines, best seller ${sku} x ${quantity}`);}Output:
3 lines, best seller SKU-RED-01 x 6Writing const pair: SkuCount = [6, "SKU-RED-01"]; fails with error TS2322: Type 'number' is not assignable to type 'string'. for the first position (and a matching error for the second).
Pitfalls:
- Mutable tuples can grow.
pushis allowed on[string, number]; declarereadonly [string, number]when the shape must not change. - Array literals are not tuples.
["SKU-RED-01", 6]is inferred as(string | number)[]unless the target type is a tuple, as with the return type above.
Complete working result
Section titled “Complete working result”The complete daily summary combines all four sections:
type SkuCount = readonly [sku: string, quantity: number];
interface OrderLine { sku: string; quantity: number; unitPrice: number;}
interface Order { id: string; lines: OrderLine[];}
function fail(message: string): never { throw new Error(message);}
function isOrderLine(value: unknown): value is OrderLine { return ( typeof value === "object" && value !== null && "sku" in value && typeof value.sku === "string" && "quantity" in value && typeof value.quantity === "number" && "unitPrice" in value && typeof value.unitPrice === "number" );}
function parseOrder(json: string): Order { const data: unknown = JSON.parse(json); if (typeof data === "object" && data !== null && "id" in data && "lines" in data) { if (typeof data.id === "string" && Array.isArray(data.lines) && data.lines.every(isOrderLine)) { return { id: data.id, lines: data.lines }; } } return fail(`Invalid order: ${json}`);}
function bestSeller(orders: readonly Order[]): SkuCount | undefined { const counts = new Map<string, number>(); for (const line of orders.flatMap((o) => o.lines)) { counts.set(line.sku, (counts.get(line.sku) ?? 0) + line.quantity); } let best: SkuCount | undefined; for (const [sku, quantity] of counts) { if (best === undefined || quantity > best[1]) best = [sku, quantity]; } return best;}
const incoming = [ '{"id":"ORD-1","lines":[{"sku":"SKU-RED-01","quantity":2,"unitPrice":19.95}]}', '{"id":"ORD-2","lines":[{"sku":"SKU-BLU-02","quantity":1,"unitPrice":5},{"sku":"SKU-RED-01","quantity":1,"unitPrice":19.95}]}', '{"id":"ORD-3","lines":[{"sku":"SKU-BLU-02","quantity":"one"}]}',];
const orders: Order[] = [];for (const json of incoming) { try { orders.push(parseOrder(json)); } catch (error) { console.log(`skipped: ${error instanceof Error ? error.message.slice(0, 30) : error}...`); }}
const revenue = orders .flatMap((o) => o.lines) .reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);const best = bestSeller(orders);
console.log(`${orders.length} orders, revenue ${revenue.toFixed(2)} EUR`);console.log(best ? `best seller: ${best[0]} (${best[1]})` : "no sales");Output:
skipped: Invalid order: {"id":"ORD-3","...2 orders, revenue 64.85 EURbest seller: SKU-RED-01 (3)Troubleshooting
Section titled “Troubleshooting”| Error | What it means | Fix |
|---|---|---|
TS2322: Type 'string' is not assignable to type 'number'. |
A value does not match the declared type. | Convert the value (Number(text)) or correct the annotation. |
TS2345: Argument of type 'string' is not assignable to parameter of type ... |
A call passes the wrong type. | Check the parameter’s type; for literal unions, use const or annotate the variable. |
TS7006: Parameter 'x' implicitly has an 'any' type. |
A parameter has no annotation and nothing to infer it from. | Annotate it: (x: number). |
TS18046: 'data' is of type 'unknown'. |
You used an unknown value without checking it. |
Narrow it with typeof, in or a type guard first. |
Check your understanding
Section titled “Check your understanding”- What is the inferred type of
let status = "paid", and ofconst status = "paid"? Why do they differ? - When would you choose
unknownoverany? - What is the return type of a function that always throws, and why is it useful?
- Why is
["SKU-RED-01", 6]not a tuple unless the target type says so?
Answers: (1) string and the literal type "paid"; a let can be reassigned, a const cannot. (2) For any value whose type you do not know yet, such as parsed JSON: unknown forces a check before use, any skips all checks. (3) never; the compiler knows code after the call is unreachable, and never is how exhaustiveness checks work. (4) Array literals are inferred as arrays, (string | number)[]; a tuple type annotation or return type makes them tuples.
Next steps
Section titled “Next steps”Continue with Functions and generics, which types parameters, optional values and return types, and writes your first generic function.
Related pages
Section titled “Related pages”- TypeScript basics overview
- Core type system: union types, tuples and literal types in depth.
- Type narrowing: checking
unknownvalues and union members.