Skip to content

Lesson 35 of 50TypeScript

Basic Types

Annotate and infer primitives, arrays and tuples, and choose between any, unknown, never, literals and enums.

15 min read0/5 questions

Every TypeScript codebase is built from the same small set of basic types. Knowing exactly what unknown, never, a tuple or a literal type means is what separates "I added some types" from code a reviewer trusts, and interviewers love asking about any versus unknown.

Annotations and inference

You can write a type after a colon. That is an annotation.

let username: string = "ada";
let age: number = 36;
let isAdmin: boolean = false;

Most of the time you do not need to. TypeScript works the type out from the value. That is type inference.

let username = "ada";   // inferred: string
let age = 36;           // inferred: number
 
age = "thirty-six";
// Error: Type 'string' is not assignable to type 'number'.

The usual style: let inference handle local variables, and annotate function parameters (TypeScript cannot guess what callers will pass) and public return types (so a mistake inside the function is reported there, not at every caller).

There are only three everyday primitive types: string, number (integers and decimals alike, there is no separate int), and boolean. They are lowercase. String with a capital S is the wrapper object type, which you never want.

Quick check
What type does TypeScript infer for each variable?
let a = "hello";
const b = "hello";
Need a nudge? A hint rules out a wrong answer.

Arrays and tuples

An array type is the element type followed by []. The generic spelling Array<number> means the same thing.

const scores: number[] = [90, 72, 85];
const names: Array<string> = ["Ada", "Sam"];
 
scores.push("100");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

A tuple is a fixed-length array where each position has its own type. React's useState returns one: [value, setValue].

TypeScript
const point: [number, number] = [3, 4];const entry: [string, number] = ["Ada", 36]; const [name, age] = entry;console.log(name.toUpperCase(), age + 1); // Object.entries gives you an array of tuplesconst stock = { apples: 3, pears: 0 };for (const [fruit, count] of Object.entries(stock)) { console.log(fruit, count);}
Output
Press Run (⌘ Enter) to see what happens.
const entry: [string, number] = [36, "Ada"];
// Error: Type 'number' is not assignable to type 'string'.

any, unknown and never

These three are special, and they are easiest to understand as the top and bottom of a ladder. Types higher up accept more values.

From every value to no value
  1. unknownAny value can go in. You must check it before using it.
  2. string | numberA union: either one
  3. stringEvery string
  4. "ok"A literal type: exactly one value
  5. neverNo value at all. Code that cannot happen.

unknown is the top type: every value is assignable to it. It is the honest type for data you have not checked yet.

1/3

any means "stop checking". You can do anything with an any and assign it anywhere. It spreads silently: one any from JSON.parse flows into everything it touches.

unknown also accepts any value, but you cannot use it until you narrow it (prove what it is with a check like typeof). That makes it the safe choice for external data.

let a: any = JSON.parse('"hello"');
a.toFixed(2);          // compiles, crashes at runtime
 
let u: unknown = JSON.parse('"hello"');
u.toUpperCase();
// Error: 'u' is of type 'unknown'.
 
if (typeof u === "string") {
  u.toUpperCase();     // OK: narrowed to string
}

never is the type with no values. You see it as the return type of a function that never returns normally, and as what is left when every possibility has been handled (you will use that for exhaustiveness checks in the unions lesson).

function fail(message: string): never {
  throw new Error(message);
}
Quick check
Which line compiles?
const raw: unknown = getInput();
Need a nudge? A hint rules out a wrong answer.

null, undefined and strictNullChecks

With strict mode on (always on in new projects), null and undefined are not part of other types. A string is never null. If a value might be missing, you say so with a union.

function findUser(id: number): User | undefined { /* ... */ }
 
const user = findUser(7);
console.log(user.name);
// Error: 'user' is possibly 'undefined'.
 
console.log(user?.name);              // OK: optional chaining
console.log(user ? user.name : "-");  // OK: narrowed by the check

This single setting, strictNullChecks, prevents the most common JavaScript error of all: "Cannot read properties of undefined". Before TypeScript 2.0 it did not exist, and null was allowed everywhere.

Literal types and as const

A literal type is a type with exactly one value, like "GET" or 404. Combine literals with | (a union, "this or that") and you get a precise set of allowed values.

type Method = "GET" | "POST" | "PUT" | "DELETE";
 
function request(url: string, method: Method) { /* ... */ }
 
request("/api/users", "GET");    // OK
request("/api/users", "FETCH");
// Error: Argument of type '"FETCH"' is not assignable to parameter of type 'Method'.

Object and array literals are widened, so { method: "GET" } is inferred as { method: string }. Add as const to keep the exact literals and make everything readonly.

TypeScript
const ROLES = ["admin", "editor", "viewer"] as const;// type: readonly ["admin", "editor", "viewer"] type Role = (typeof ROLES)[number];// "admin" | "editor" | "viewer" function isRole(value: string): value is Role { return (ROLES as readonly string[]).includes(value);} console.log(isRole("editor"), isRole("owner"));
Output
Press Run (⌘ Enter) to see what happens.

That pattern (one as const array, one derived union) gives you a list you can loop over at runtime and a type, from a single source of truth.

Quick check
What type does TypeScript infer for config.mode?
const config = { mode: "dark" };
Need a nudge? A hint rules out a wrong answer.

Enums vs unions of literals

TypeScript has an enum keyword, one of the few features that is not erased. It generates a real JavaScript object.

TypeScript
enum Direction { Up, Down, Left, Right,} console.log(Direction.Left);console.log(Direction[3]);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

What does this print?

enum Status { Draft, Published, Archived }
console.log(Status.Published, Status[2]);
Need a nudge? Hints walk you through it.

Many teams avoid enums and use a union of string literals instead:

enum Status { Draft, Published }type Status = "draft" | "published"
Runtime codeGenerates an objectErased completely
Values in JSON / logs0, 1 (opaque numbers)"draft" (readable)
Works with type-stripping toolsNo (Node's --strip-types rejects it)Yes
AutocompleteYesYes

Unions are plain JavaScript values, read well in API payloads, and work with tools that only delete types (Node.js type stripping and the erasableSyntaxOnly compiler flag both reject enums). If you need the values at runtime too, use the as const array pattern above.

Match the pairs0/5 matched

Match each value to the best type.

Choose an item, then its match on the other side.
ChallengeEasy

Min and max as a tuple

Write minMax(nums: number[]): [number, number] | null. It returns a tuple [smallest, largest], or null when the array is empty.

minMax([3, 1, 2])   →  [1, 3]
minMax([5])         →  [5, 5]
minMax([])          →  null

Do it in a single pass. Do not sort (sorting is O(n log n) and mutates the input).

TypeScript
function minMax(nums: number[]): [number, number] | null { // Return null for an empty array, otherwise [min, max]. return null;}
ChallengeEasy

Classify an HTTP status

Write statusClass(code: number): StatusClass, where the return type is a union of string literals:

type StatusClass = "info" | "success" | "redirect" | "client-error" | "server-error" | "unknown";
  • 100–199 → "info", 200–299 → "success", 300–399 → "redirect"
  • 400–499 → "client-error", 500–599 → "server-error"
  • anything else (including non-integers) → "unknown"
statusClass(404)  →  "client-error"
statusClass(42)   →  "unknown"
TypeScript
type StatusClass = "info" | "success" | "redirect" | "client-error" | "server-error" | "unknown"; function statusClass(code: number): StatusClass { return "unknown";}
Key terms
type inference
TypeScript working out a type from a value, so you do not have to annotate it.
tuple
A fixed-length array type with a type per position, like [string, number].
unknown
The safe top type: any value fits, but you must narrow it before using it.
never
The bottom type with no values. Used for functions that never return and for impossible cases.
literal type
A type with exactly one value, like "GET" or 404. Unions of literals model fixed sets of options.
as const
Keeps literal types and makes an object or array deeply readonly.