The Analogy: The Stores Counter and Its Bin Cards
Walk into the maintenance stores of any factory and you will find racks of bins, and every bin carries a printed label and a bin card. The label gives the part number and the description. The card gives the unit of issue: each, metre, litre, kilogram. A fitter arrives at the counter and asks for four of part 118-6; the storeman reads the label, counts four out of that bin, and writes the withdrawal on the card. Nobody rummages, because the labels mean the racks can be trusted without opening every bin.
The label is doing two separate jobs, and it is worth separating them. It says what may go in the bin, and it says how the contents are counted. "M8 plain washers, unit of issue: each" and "brake cleaner, unit of issue: litre" are not merely different parts; they are different kinds of quantity. You cannot ask for two and a half washers, and asking for "one" brake cleaner is a question rather than an order. Experienced fitters read the unit of issue before they read the part name, because that is the part that changes how you have to think.
The discipline is cheap to keep and expensive to lose. A fitter in a hurry who tips a handful of washers into the bolt bin has saved himself thirty seconds and created a bin that nobody can ever trust again, because from then on every withdrawal from it needs a hand inspection. Every stores also has the bin labelled MISC, and everyone knows what it means: it holds whatever anyone put there. The MISC bin is not free -- its cost is that no withdrawal from it can be believed without opening it up and looking.
The failure mode is precise: a label is a claim about contents, and it is only checked when somebody looks. There are two ways it goes wrong. The first is the bin whose part was superseded a year ago and whose label was never changed, so the label describes something accurate about a part that no longer exists. The second is the bin somebody re-filled in a hurry with what was to hand. From the counter these two look exactly like a correct bin, and that is the whole problem: the label tells you what the bin is supposed to contain, and reading it is not the same as looking inside.
Syntax or Core Structure
TypeScript has seven primitive types, and they are the JavaScript primitives with names attached. An annotation goes after the colon; the value goes after the equals sign.
// primitives.ts
let username: string = "Alice";
let age: number = 30;
let active: boolean = true;
let big: bigint = 9007199254740993n;
const tag: symbol = Symbol("row-id");
console.log(typeof username, typeof age, typeof active);
console.log(typeof big, typeof tag);
console.log(username + " is " + age + ", active=" + active);
console.log("big=" + big.toString());
console.log("tag=" + tag.toString());
Output:
string number boolean
bigint symbol
Alice is 30, active=true
big=9007199254740993
tag=Symbol(row-id)
Three of those five annotations could have been dropped without losing anything, because username, age and active are all inferred from their initialisers. The bigint literal ends in n and requires target set to es2020 or later, since there is no way to compile arbitrary-precision integers down to an older JavaScript. Symbol("row-id") produces a value guaranteed unique for the life of the program; the string inside is a description for debugging and not an identity, so two symbols built from the same string are still two different values.
The two empty primitives deserve their own block, because one of them misreports itself:
let nothing: null = null;
let notSet: undefined = undefined;
console.log(typeof nothing, typeof notSet);
console.log(String(nothing), String(notSet));
console.log(nothing ?? "fallback", notSet ?? "fallback");
Output:
object undefined
null undefined
fallback fallback
typeof null answering object is a bug from 1995 that cannot be fixed without breaking a large part of the web, so it is now a permanent feature. The distinction that matters day to day is intent: undefined means nobody has set this, while null means somebody set it to nothing on purpose. TypeScript takes the difference seriously enough that writing nothing === undefined on a variable declared null is itself an error (TS2367, "no overlap"), which is the compiler refusing to let you write a comparison whose answer it already knows.
Technical Depth: Seven Primitives, One Number Type
The full set
| Type | A value of it | What typeof answers |
|---|---|---|
string | "Alice" | string |
number | 30 or 3.5 | number |
boolean | true | boolean |
bigint | 9007199254740993n | bigint |
symbol | Symbol("row-id") | symbol |
null | null | object, the 1995 bug |
undefined | undefined | undefined |
Everything else in JavaScript is an object, arrays and functions and dates included. That is the entire inventory, and it is smaller than most languages offer: there is no char, no int, no float, no decimal, and nothing unsigned.
One number type, and what it costs
number is an IEEE 754 double. Every integer, every fraction, every array index and every millisecond timestamp in JavaScript is the same 64-bit floating point value. That buys real simplicity, and it charges for it in three places:
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log((0.1 + 0.2).toFixed(2));
console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MAX_SAFE_INTEGER + 2);
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2);
console.log(7 / 2, Math.trunc(7 / 2), 7 % 2);
console.log(Number.isInteger(3.0), Number.isInteger(3.5));
Output:
0.30000000000000004
false
0.30
9007199254740991
9007199254740992
true
3.5 3 1
true false
The first three lines are the money problem. One tenth cannot be written exactly in binary any more than one third can be written exactly in decimal, so a program that adds prices as number will eventually produce a total that is wrong by a fraction of a penny and then print it. The remedy is not toFixed, which merely hides the residue at the last moment; the remedy is to hold money as an integer count of pence and divide once, at the edge, on the way to the screen.
The next three lines are the identifier problem. Integers are exact only up to two to the power fifty-three. Past that boundary the odd numbers stop existing, so adding one and adding two to MAX_SAFE_INTEGER land on the same value and compare equal. This is why a 64-bit database id has to travel as a string or a bigint, and why an API that sends one as a JSON number has already corrupted it before your code is involved.
The last two lines are the division problem. There is no integer division: 7 / 2 is 3.5, and if you wanted three you must say which three with Math.trunc or Math.floor, which disagree on negative numbers. Number.isInteger(3.0) answers true because 3.0 and 3 are not two values that happen to be equal; they are the same value, and nothing records that you typed a decimal point.
Literal types and widening
A string literal is also a type. "read" is a type with exactly one member, and a union of such types is how you fence a parameter down to the labels you actually support:
type Mode = "read" | "write";
function open(path: string, m: Mode): string {
return "opening " + path + " for " + m;
}
const fixed = "read";
const holder = { mode: "read" };
console.log(open("hosts.txt", fixed));
console.log(open("notes.txt", "write"));
console.log(open("fstab", holder.mode as Mode));
Output:
opening hosts.txt for read
opening notes.txt for write
opening fstab for read
The three lines are identical at runtime and quite different at compile time. fixed is a const, so it can never hold anything else and TypeScript keeps its narrow literal type. holder.mode is a mutable property, so at the moment the object was built the compiler widened it to string -- something could assign "delete" to it later. Passing it without the assertion is a TS2345, and the as Mode in that third call is not a fix; it is a written promise that you have checked something the compiler cannot see.
Widening is worth learning as a table rather than as a surprise:
| Declaration | Type of the value passed | Accepted by open |
|---|---|---|
const fixed = "read" | the literal type "read" | yes |
let loose = "read" | string | no |
const holder = { mode: "read" } | string | no |
const holder = { mode: "read" } as const | the literal type "read" | yes |
const holder: { mode: Mode } = { mode: "read" } | the Mode union | yes |
The last two rows are the honest fixes, and the annotation is the better of them: it says what the field is allowed to be, so a later holder.mode = "delete" is rejected at the assignment rather than smuggled through to the call.
The wrapper objects, and why you never want one
Each primitive has a matching object type spelled with a capital letter, and they are not interchangeable:
console.log(typeof "cash", typeof new String("cash"));
console.log("cash" === new String("cash").valueOf());
console.log(new String("cash").length, "cash".length);
Output:
string object
true
4 4
A wrapper is a full object that happens to contain a string. It answers "object" to typeof, it is never === to the primitive it wraps (only its valueOf() is), and two wrappers around the same text are two different objects. The lowercase names are the ones you annotate with; the capitalised names have exactly one legitimate use, which is calling String(x) or Number(x) as a plain function to convert.
| Written | What it denotes | When to use it |
|---|---|---|
string, number, boolean | the primitive value itself | in every annotation you ever write |
String, Number, Boolean | the wrapper object type, and the global conversion function | only as a call, never as a type |
Strings are UTF-16 code units
string is a sequence of 16-bit code units, and length counts units rather than characters. The samples below spell every non-ASCII character as an escape so that what you read is exactly what the compiler reads:
const cafe = "caf\u00e9";
const grin = "\u{1F600}";
const sharpS = "\u00df";
console.log(cafe.length, [...cafe].length);
console.log(grin.length, [...grin].length);
console.log(cafe.codePointAt(3));
console.log(grin.codePointAt(0));
console.log(sharpS.length, sharpS.toUpperCase().length);
Output:
4 4
2 1
233
128512
1 2
The accented word behaves: four units, four characters. The emoji does not. It is one character stored as two units, so length says 2, spreading it into an array says 1, and slice(0, 1) would hand you half of a surrogate pair -- a string that is not text. The last line is the other trap: upper-casing can change how many characters there are, because the capital form of the sharp s is two letters.
None of this is visible in the type. There is one string type and it carries no length, no encoding and no promise of well-formedness, so the compiler will happily let you truncate a message at twenty units and mail out a broken character. If a limit matters, count with the spread form or Intl.Segmenter, and let length mean only what it means: storage units.
Real World Example: A Quarter's Meter Billing Run
Every primitive in the language earns its place in one small program: the meter reference is a string, the readings and the money are number, the estimate flag is a boolean, and the meter's serial is a bigint because it is an identifier that will not survive being a double. Money is held as an integer count of pence from the first line to the last, and converted to pounds exactly once, on the way to the screen.
// meter.ts (compiled with "target": "es2020" for the bigint literals)
type Reading = {
meter: string;
serial: bigint;
previous: number;
current: number;
estimated: boolean;
};
const TARIFF_PENCE_PER_UNIT = 27;
const STANDING_CHARGE_PENCE = 4500;
const READINGS: Reading[] = [
{ meter: "M-001", serial: 9007199254740993n, previous: 10420, current: 10680, estimated: false },
{ meter: "M-002", serial: 9007199254740995n, previous: 8875, current: 8875, estimated: true },
{ meter: "M-003", serial: 9007199254740997n, previous: 30115, current: 30500, estimated: false },
];
function unitsUsed(r: Reading): number {
return r.current - r.previous;
}
function penceFor(units: number): number {
return units * TARIFF_PENCE_PER_UNIT + STANDING_CHARGE_PENCE;
}
function poundsFromPence(pence: number): string {
const pounds = Math.trunc(pence / 100);
const remainder = pence - pounds * 100;
return "GBP " + pounds + "." + String(remainder).padStart(2, "0");
}
function pad(text: string, width: number): string {
return text + " ".repeat(Math.max(0, width - text.length));
}
function billingRun(readings: Reading[]): string {
const lines: string[] = [pad("METER", 8) + pad("UNITS", 8) + pad("PENCE", 9) + "BILL"];
const estimates: string[] = [];
let totalPence = 0;
for (const r of readings) {
const units = unitsUsed(r);
const pence = penceFor(units);
totalPence = totalPence + pence;
if (r.estimated) {
estimates.push(r.meter + " (serial " + String(r.serial) + ")");
}
lines.push(pad(r.meter, 8) + pad(String(units), 8) + pad(String(pence), 9) + poundsFromPence(pence));
}
lines.push(pad("TOTAL", 8) + pad("", 8) + pad(String(totalPence), 9) + poundsFromPence(totalPence));
lines.push("estimated readings: " + (estimates.length === 0 ? "none" : estimates.join(", ")));
return lines.join("\n");
}
console.log(billingRun(READINGS));
Output:
METER UNITS PENCE BILL
M-001 260 11520 GBP 115.20
M-002 0 4500 GBP 45.00
M-003 385 14895 GBP 148.95
TOTAL 30915 GBP 309.15
estimated readings: M-002 (serial 9007199254740995)
Every figure on that report can be checked by hand, which is the only reason to trust it. M-001 turned 260 units; at 27 pence each that is 7020 pence, and with the 4500 pence standing charge the bill is 11520 pence, printed as GBP 115.20. M-002 turned nothing at all and still owes the standing charge, so 4500 pence and GBP 45.00. M-003's 385 units come to 10395 pence, so 14895 with the charge. The three bills sum to 30915 pence, and the single division in the whole program turns that into the GBP 309.15 on the TOTAL line. The columns are fixed by construction rather than by eye: the meter reference occupies eight characters, units the next eight, pence the next nine, so the bill text always begins at character 25.
Each primitive is doing a job only it can do. The serial prints as 9007199254740995 because it is a bigint; declared as number that literal would have been rounded to the nearest representable double on the way in, the line would read 9007199254740996, and the report would name a meter that does not exist -- with no error, no warning and nothing in a test to notice. The boolean is read by an explicit if rather than left to a truthiness test, and the estimate note is assembled from the meters that actually set the flag. The money never becomes a fraction: penceFor returns whole pence, the running total adds whole pence, and poundsFromPence splits pounds from remainder with Math.trunc and integer subtraction rather than trusting toFixed to tidy up a drifting decimal at the end.
The annotations pay for themselves in the boring cases. Reading names five fields with four different types, so r.currrent is a compile error rather than undefined, and unitsUsed therefore cannot return NaN because of a typo. Mixing serial into arithmetic is rejected outright, since TypeScript refuses to add a bigint to a number. Passing a whole Reading where a unit count belongs is rejected too. What the annotations cannot do is tell two numbers apart: penceFor, poundsFromPence and pad all take plain number parameters, so handing pounds to a function that expects pence, or a width to a function that expects money, type-checks perfectly and prints a wrong bill.
That gap is where this program's real defects live, and there are three. First, unitsUsed trusts subtraction: a five-digit mechanical meter that rolls over from 99500 to 00405 yields -99095 units, and poundsFromPence then computes a negative remainder and concatenates it, so the customer's bill reads GBP -26710.-65 -- a malformed string, a large credit, and no exception anywhere. Second, penceFor accepts fractions, because number has no integer variant: a smart meter reporting 10680.5 gives 260.5 units and 11533.5 pence, and the printed bill becomes GBP 115.33.5, since padStart cannot pad a string that is already longer than two characters. Third, pad truncates nothing and widens nothing when a value overflows its column, so one meter with a seven-figure pence total shifts the BILL column right and quietly breaks every downstream parser. The type system flagged none of the three, and it never could have: all three are statements about which numbers are legal, and number says only that a number arrived.
Common Mistakes
- Annotating with the capitalised wrapper names.
let name: Stringcompiles, and then rejects nothing useful while quietly acceptingnew String("x"), whosetypeofis"object"and which is never===to a plain string. The primitive types are lowercase without exception:string,number,boolean,bigint,symbol. The capitalised names are conversion functions, andString(x)called withoutnewis the only form you want. - Holding money as a fractional
number. Prices added as pounds accumulate binary residue until a total prints as 41.410000000000004, andtoFixed(2)only conceals the last one -- it returns astring, it rounds in ways that surprise people ((1.005).toFixed(2)is"1.00"), and it cannot undo an error that has already been added into a running total. Hold integer pence, add integers, divide once when you print. - Putting a 64-bit identifier in a
number. Above 9007199254740991 the odd integers do not exist, so an id ending 993 arrives as 992 and two different rows become the same row. Ids arestringif you only compare and log them,bigintif you must do arithmetic, and never a JSON number in the first place. - Reading
.lengthas a count of characters. It counts UTF-16 code units. One emoji is 2, a flag can be 4 or more, and slicing at a unit boundary produces half a surrogate pair, which is a string your database may reject and your terminal will render as a replacement character. Count with the spread form orIntl.Segmenterwhen the number is user-facing. - Expecting
typeof nullto be"null". It is"object", a bug preserved deliberately for compatibility, sotypeof x === "object"is true fornulland any code that then reads a property throws. Test for null withx === null, and remember thatnullandundefinedare two different primitives that only==treats as equal. - Mixing
bigintandnumberin one expression.1n + 1is a compile error and remains aTypeErrorat runtime, because there is no implicit conversion in either direction. Convert deliberately withBigInt(n)orNumber(b), accepting that the second can lose precision, and note thatJSON.stringifythrows on abigintrather than serialising it -- so a bigint id has to be converted to a string before it can be sent anywhere. - Trusting a conversion to act as validation.
Number("")is 0,Number(" 12 ")is 12,Number("12px")isNaN, andparseInt("12px")is 12 because it stops at the first character it cannot use. Any of those silently turns a bad form field into a plausible figure. Validate the string first, then convert. - Treating
NaNas something you can compare.typeof NaNis"number",NaN === NaNisfalse, and the globalisNaNcoerces its argument soisNaN("abc")istruefor the wrong reason. UseNumber.isNaNfor the test andNumber.isFinitefor the check you usually meant, and treat aNaNappearing in a total as a bug upstream rather than a value to filter out downstream. - Reaching for
aswhen the real problem is widening. Whenobj.modewill not go into a parameter typed as a union of literals, an assertion silences the message and keeps the hole; the property really isstringand really could hold anything. Annotate the object or the property with the union, or fix the value in place withas const, so that the wrong assignment is rejected where it happens rather than where it is finally used.
Best Practices
- Annotate the boundaries, let inference handle the inside. Parameters, return types and exported constants are contracts and deserve written types; a local
const rate = 27does not. The rule keeps the useful annotations visible instead of drowned in restatements of the obvious. - Store exact quantities in their smallest whole unit. Pence, grams, milliseconds, basis points. Add and compare integers all the way through, and divide exactly once, at the moment of display. This turns a class of rounding bugs into an impossibility rather than a test case.
- Use a union of string literals wherever the set of values is fixed. A status, a mode, a currency code and a log level are all better as three or four literals than as
string, because the compiler can then reject the misspelling that a runtimeswitchwould silently fall through. - Pin literal values with an annotation, or
as constif you cannot. An annotated object property keeps its narrow type and rejects a bad assignment at the assignment. Reserveasfor the genuine cases where you know something the compiler cannot, and treat each one as a comment saying "trust me". - Turn on
strictand leave it on. UnderstrictNullChecks,nullandundefinedstop hiding inside every other type and start appearing in signatures where they belong, which converts a runtime "cannot read property of undefined" into a compile error at the one place the value could have been missing. - Write the lowercase type names and the capitalised functions.
stringandnumberin annotations;String(x)andNumber(x)as calls;Number.isNaN,Number.isFiniteandNumber.isIntegerfor the tests, never their coercing global counterparts and nevernew. - Validate a string before converting it, not after. Check the shape with a regular expression or a schema, then convert, then use. A conversion that returns 0 for an empty field or 12 for
"12px"has already destroyed the evidence that the input was wrong. - Spell non-ASCII characters as escapes in source, and count characters on purpose.
"\u00e9"reads identically on every machine and in every editor, and it forces the question of whether the length you are about to check is a count of storage units or of characters the reader can see.
Practice Exercises
- Close the rollover hole. Change
unitsUsedso a reading wherecurrentis less thanpreviouscannot flow into the bill: return anumberonly for a valid pair and signal the invalid one some other way, then print a report where M-004 reads 99500 previous and 405 current. Confirm that no bill line contains a negative figure and that the meter is listed as needing a manual read instead. - Make fractional pence unrepresentable in practice. Add a function
toPence(value: number): numberthat throws when its argument is not an integer, routepenceForand the running total through it, and feed the program a 10680.5 reading. Show the error message it now produces, and explain why a type annotation alone could not have preventedGBP 115.33.5. - Replace the boolean with a literal union. Swap
estimated: booleanforsourcewith the three values"meter","estimate"and"customer", print a subtotal per source, and then try to build oneReadingfrom an object literal whosesourcecame from a mutable config object. Record the exact TS2345 message, fix it without usingas, and say which fix you chose and why. - Count characters rather than units. Write
truncate(text: string, maxChars: number): stringthat never cuts a surrogate pair in half, and test it on"caf\u00e9"and on a string of three"\u{1F600}"characters. Print only the unit count and the character count of each result -- never the strings themselves -- and state whattext.slice(0, maxChars)would have printed instead.