TypeScript for real code · Chapter 2 of 36

Strings, numbers and exact values

By the end of this chapter you can say exactly which values a type allows: two cup sizes and nothing else, a number or no answer at all, a whole number of any size. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Why types
  • 4 tasks
  • TypeScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Anjali spent a morning on apologies. A customer ordered a medium masala chai on the app, but Tapri sells only small cups (₹25) and large kulhads (₹40). The app charged ₹40 and the kitchen made a small. The same week, Ravi found orders for 0 cups: the quantity box was left blank, and the app read it as 0. And two UPI payments came out with the same transaction id, because a 19-digit id does not fit exactly in a number.

The types from chapter 1 are too wide for all three. size: string accepts 'medium', 'Large' and 'chai'. A return type of number has no way to say "there is no quantity", so Bunty returned 0, which is also a real quantity. You could add more ifs at runtime, but those run in front of the customer. TypeScript can say exactly which values are allowed, and check it before anything runs.

The lesson

Literal types

A type can be one exact value: the type 'less' allows only the text 'less'. Join a few with a bar, and you get "one of these":

function sugarSpoons(sugar: 'none' | 'less' | 'normal'): number {
  if (sugar === 'none') return 0;
  return sugar === 'less' ? 1 : 2;
}

sugarSpoons('less');
sugarSpoons('extra');
sugarSpoons('LESS');
$ typecheck demo.ts
demo.ts:7:13 - error TS2345: Argument of type '"extra"' is not assignable to parameter of type '"less" | "none" | "normal"'.

7 sugarSpoons('extra');
              ~~~~~~~

demo.ts:8:13 - error TS2345: Argument of type '"LESS"' is not assignable to parameter of type '"less" | "none" | "normal"'.

The comparison is exact, capitals and all. (TypeScript writes the members in its own order in the message; the order means nothing.)

null means "no answer"

The lab runs with strict, so null is a type of its own and is not hidden inside number. A function that may have no answer must say so in its return type:

const tables = ['rooftop', 'window', 'corner'];

function findTable(name: string): number {
  const i = tables.indexOf(name);
  return i === -1 ? null : i + 1;
}
$ typecheck demo.ts
demo.ts:5:21 - error TS2322: Type 'null' is not assignable to type 'number'.

With number | null as the return type, that function compiles, and now every caller is made to check:

const tables = ['rooftop', 'window', 'corner'];

function findTable(name: string): number | null {
  const i = tables.indexOf(name);
  return i === -1 ? null : i + 1;
}

const table = findTable('garden');
console.log(table.toFixed());
$ typecheck demo.ts
demo.ts:9:13 - error TS18047: 'table' is possibly 'null'.

9 console.log(table.toFixed());
              ~~~~~

That is a good error: there is no garden table, and running it anyway crashes with TypeError: Cannot read properties of null (reading 'toFixed').

Inside if (table !== null), TypeScript knows table is a number. (Chapter 6 is all about checks like that one.)

Reading numbers from text has a trap. Number turns text into a number and gives NaN for text that is not one, but some text with no number in it still comes out as a number:

bigint for big whole numbers

A number is exact only up to 9007199254740991. A 19-digit UPI reference is past that, and the last digits change without a word. A bigint ends in n and stays exact at any size:

const upiRef = 4012345678901234567;
const exact = 4012345678901234567n;

console.log(upiRef);
console.log(exact);
console.log(exact + 1n);
$ node demo.ts
4012345678901234700
4012345678901234567n
4012345678901234568n

The type is bigint, and the two kinds never mix: exact + 1 is an error, Operator '+' cannot be applied to types '4012345678901234567n' and '1'. Add 1n instead.

let widens, const does not

When you write no type, TypeScript infers one from the value. A const can never change, so it keeps the exact value as its type. A let could be given any other text later, so TypeScript widens it to string:

function sugarSpoons(sugar: 'none' | 'less' | 'normal'): number {
  if (sugar === 'none') return 0;
  return sugar === 'less' ? 1 : 2;
}

let usual = 'less';
const today = 'less';
sugarSpoons(usual);
sugarSpoons(today);
$ typecheck demo.ts
demo.ts:8:13 - error TS2345: Argument of type 'string' is not assignable to parameter of type '"less" | "none" | "normal"'.

8 sugarSpoons(usual);
              ~~~~~

Only one error: today has the type 'less', which fits, and usual has the type string, which could be anything.

Your turn

Your four tasks are at the top, all in exercise.ts, each with its own comment. Task 2 has the blank-box trap from the animation. Dev asks task 4 as an interview question: once task 1 is done, Bunty's houseSize line stops compiling, and he wants to know why a variable holding 'small' has the type string.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    cupPrice: only the two real cup sizes

    Tapri sells two cups: small for ₹25 and large for ₹40. cupPrice('small') is 25 and cupPrice('large') is 40.

    Change the type of size from string to 'small' | 'large', so cupPrice('medium') is a type error, and so is a size in capitals, like cupPrice('LARGE'). Keep the return type number. Once this is done, the houseSize line at the bottom stops compiling: that is task 4.

  2. Task 2

    parseQty: no quantity is null, not 0

    parseQty reads the quantity box on the order form: parseQty(' 3 ') is 3 and parseQty('0') is 0, but parseQty(''), parseQty(' ') and parseQty('two') are all null.

    A quantity of 0 is a real answer, so a blank box or text that is not a number must give null. Change the return type to number | null, so a caller has to check for null before using the quantity (calling toFixed on the result straight away is a type error). Careful: Number('') and Number(' ') are 0, not NaN, so a blank box needs its own check.

  3. Task 3

    nextTxnId: UPI transaction ids stay exact

    A UPI transaction id is 19 digits long, too big for a number to hold exactly. nextTxnId gives the id after the one it is given: nextTxnId(9007199254740993n) is 9007199254740994n.

    Make it take a bigint and return a bigint, so a plain number, like nextTxnId(42), is a type error.

  4. Task 4 · interview question

    Interview: houseSize keeps its exact type

    Bunty set the house size with let. Once task 1 is done, typecheck says the call to cupPrice on the housePrice line does not fit. houseSize is 'small' and housePrice is 25.

    Make the type of houseSize exactly 'small', not string, and leave cupPrice and the call alone. The whole file must have no type errors. Dev will ask why houseSize is a string when it holds 'small'.

What you will learn

  • Literal types: 'small' is a type with one value, and 'small' | 'large' allows exactly two.
  • null in a type: number | null says "a number, or no answer", and the caller must check before using it.
  • bigint: whole numbers of any size, written with an n at the end.
  • let and const: why let widens 'small' to string, and const keeps it exact.

More in Why types

Build "Strings, numbers and exact values" yourself

Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.