Level 3
Variables & Data Types
Master TypeScript's primitive types, learn how type inference lets you omit most annotations, and understand special types like any, unknown, and literal types.
20 min read + quiz
The Primitive Types
TypeScript's core primitives mirror JavaScript's: string, number, and boolean. Note the lowercase names: String, Number, and Boolean (capitalized) also exist but refer to JavaScript's rarely-used wrapper objects. Always annotate with the lowercase versions; using the capitalized ones is a classic beginner mistake that leads to confusing errors later.
JavaScript has a single number type covering both integers and floating-point values, and TypeScript follows suit: 42, 3.14, and -0.5 are all just number. There is also bigint for integers beyond Number.MAX_SAFE_INTEGER, and symbol for unique identifiers, though you will use those far less often.
Two more primitives deserve early attention: null and undefined. In strict mode each is its own distinct type, and neither is silently allowed where a string or number is expected. This is one of TypeScript's biggest wins over plain JavaScript, where a stray undefined can travel through your program and explode far from its source.
let title: string = "TypeScript Academy";
let level: number = 3;
let published: boolean = true;
let views: bigint = 9007199254740993n;
// Strict mode keeps null/undefined out of other types:
// let name: string = null;
// Error: Type 'null' is not assignable to type 'string'.
let maybeName: string | null = null; // opt in explicitly
maybeName = "Ada";The lowercase primitives, plus explicit opt-in for null via a union type.
Type Inference: Let the Compiler Work
You do not need to annotate everything. When you initialize a variable, TypeScript infers its type from the value: 'let count = 0' makes count a number without any annotation. Idiomatic TypeScript leans heavily on inference; annotations everywhere add noise without adding safety.
Inference interacts with mutability. A 'let' variable initialized with "hello" is inferred as string, because you might reassign it to another string later. But a 'const' initialized with "hello" is inferred as the literal type "hello", the type whose only value is that exact string, since a const can never change.
So when should you write annotations? Three main places: function parameters (which cannot be inferred from a value), function return types when you want an explicit contract, and variables that you declare before assigning. Everywhere else, prefer letting the compiler infer.
let count = 0; // inferred: number
let greeting = "hello"; // inferred: string
const exact = "hello"; // inferred: the literal type "hello"
count = 10; // fine
// count = "ten"; // Error: not a number
// Annotate when there is no initializer to infer from:
let pending: string;
pending = "loaded";Inference handles most variables. const narrows to a literal type; let widens to the general type.
any vs unknown: The Escape Hatches
The type 'any' disables checking entirely: you can assign anything to it, call any method on it, and pass it anywhere. It exists for migration from JavaScript and for genuinely untypeable code, but every 'any' is a hole in your safety net, and the hole spreads, since operations on any produce more any.
'unknown' is the safe alternative. Like any, it accepts every value, but unlike any, it lets you do nothing with the value until you narrow it. You must prove what it is, with typeof, instanceof, or another check, before using it. This is exactly the right type for JSON.parse results, catch-clause errors, and other data whose shape you cannot promise.
Rule of thumb: reaching for any should feel like a code smell. If you truly do not know a value's type, say so honestly with unknown, and let the compiler force you to check before you touch it.
const risky: any = JSON.parse('{"n": 1}');
risky.does.not.exist; // compiles, crashes at runtime
const safe: unknown = JSON.parse('{"n": 1}');
// safe.n; // Error: 'safe' is of type 'unknown'
if (typeof safe === "object" && safe !== null && "n" in safe) {
console.log("Validated:", safe); // narrowed, now usable
}any silently permits crashes; unknown forces you to validate before use.
Literal Types and Unions
TypeScript can type a variable not just as 'some string' but as one specific string. The type "left" has exactly one value. On its own that seems useless, but combined with the union operator (|) it becomes one of TypeScript's most-used patterns: a value that must be one of a fixed set of options.
Writing direction: "left" | "right" | "up" | "down" gives you an enum-like type with zero runtime cost, full autocomplete, and compile-time protection against typos. Pass "lefft" and the compiler stops you immediately, something plain JavaScript strings could never do.
Unions are not limited to literals: string | number is a value that could be either, and TypeScript will only let you use operations valid for both until you narrow it with a typeof check. This narrowing behavior, called control-flow analysis, runs through everything you will do in TypeScript.
type Direction = "left" | "right" | "up" | "down";
function move(dir: Direction): string {
return "Moving " + dir;
}
move("left"); // OK, with autocomplete for all four options
// move("lefft"); // Error: not assignable to type 'Direction'
function describe(id: string | number): string {
if (typeof id === "number") {
return "#" + id.toFixed(0); // narrowed to number here
}
return id.toUpperCase(); // narrowed to string here
}Literal unions catch typos at compile time; typeof narrows a union inside each branch.
let, const, and Why var Is Gone
TypeScript inherits JavaScript's three declaration keywords, but in practice you should use exactly two: const by default, and let when reassignment is genuinely needed. Never use var: it is function-scoped rather than block-scoped, it hoists in surprising ways, and TypeScript's types cannot protect you from the bugs var invites.
Preferring const is not just style. As you saw with literal inference, const gives TypeScript more precise information, which produces better checking downstream. A const object's variable binding cannot be reassigned, though note that the object's contents remain mutable; const freezes the binding, not the value.
This distinction matters: 'const user = { name: "Ada" }' prevents 'user = otherUser' but allows 'user.name = "Grace"'. If you need deep immutability, TypeScript offers readonly properties and 'as const' assertions, which you will meet in later lessons.
const user = { name: "Ada", level: 3 };
// user = { name: "Grace", level: 4 }; // Error: cannot reassign
user.name = "Grace"; // Allowed: contents mutable
let attempts = 0;
attempts = attempts + 1; // let permits reassignment
// var leaks out of blocks - one reason it is banned in practice:
// if (true) { var leaky = "oops"; }
// console.log(leaky); // visible here with var!const prevents reassignment of the binding, not mutation of the object it points to.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
Which annotation is correct idiomatic TypeScript for a text value?
Question 2 · Predict the output
What does this program print?
function formatId(id: string | number): string {
if (typeof id === "number") {
return "#" + id.toFixed(2);
}
return id.toUpperCase();
}
console.log(formatId(7));
console.log(formatId("abc"));Question 3 · True or false
A variable of type unknown can have its properties accessed directly, just like a variable of type any.
Question 4 · Find the error
This code fails to compile in strict mode. Where is the error?
type Theme = "light" | "dark";
let current: Theme = "light";
current = "dark";
current = "midnight";
console.log(current);Question 5 · Multiple choice