TypeScript for real code · Chapter 1 of 36
Your first types
By the end of this chapter you can give a function's parameters and its result a type, and read the errors TypeScript gives when a call does not fit. 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
Meera found a bill for ₹402 for one masala chai. The menu tablet had sent the price as the text '40', and the billing code added GST to it: JavaScript glued '40' and 2 together instead of adding them. A week before, a receipt printed "undefined" where a line should have been.
JavaScript never asks what a function was given. The only way to find these bugs is to run the code, and at Tapri a customer usually runs it first. Bunty wanted to add an if (typeof price !== 'number') to every function, but that check still runs at the counter, in front of the customer, and he would forget it in half the functions. Kabir has moved the billing file to TypeScript, which checks every call before the code ever runs.
The lesson
Types on parameters
Here is a tip added to a bill, in plain JavaScript:
function withTip(bill, tip) {
return bill + tip;
}
console.log(withTip(120, 10));
console.log(withTip(120, '10'));
$ node demo.ts
130
12010
TypeScript is JavaScript with types. You write a type after a colon: the parameters' types inside the brackets, the result's type after them. Now the wrong call is caught:
function withTip(bill: number, tip: number): number {
return bill + tip;
}
withTip(120, 10);
withTip(120, '10');
$ typecheck demo.ts
demo.ts:6:14 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
6 withTip(120, '10');
~~~~
Found 1 error in demo.ts:6
Press Next to put five calls through both versions:
Types are only checked, never run. node demo.ts strips them out and runs what is left, so a typed file with a wrong call in it still runs, and still prints 12010. Run typecheck first.
Strict mode: no silent any
The lab uses TypeScript's strict settings, like every serious project. A parameter with no type is an error, because TypeScript would otherwise give it the type any, which accepts everything and checks nothing:
$ typecheck demo.ts
demo.ts:1:18 - error TS7006: Parameter 'bill' implicitly has an 'any' type.
1 function withTip(bill, tip) {
~~~~
Bunty's favourite way out is to write bill: any, tip: any. Then typecheck prints No type errors. and node demo.ts still prints 12010: the error is gone, and so is the check. You do not need to type everything, though: TypeScript infers the type of let qty = 2 (a number) from its value. You write types where it cannot know, and parameters are the first place.
Lists
A list of one type is the type followed by []:
function cheapest(prices: number[]): number {
return Math.min(...prices);
}
cheapest([40, 25, 30]);
cheapest(40);
cheapest(['40', '25']);
$ typecheck demo.ts
demo.ts:6:10 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'number[]'.
6 cheapest(40);
~~
demo.ts:7:11 - error TS2322: Type 'string' is not assignable to type 'number'.
One number is not a list of numbers, and every element of the list is checked.
A return type is a promise
With no return type written, TypeScript works one out from every return in the function. A bare return; gives back undefined, and that is how "undefined" ends up on a receipt:
function cupSize(ml: number) {
if (ml >= 200) return 'large';
if (ml > 0) return 'small';
return;
}
console.log(`Your cup: ${cupSize(250)}`);
console.log(`Your cup: ${cupSize(0)}`);
$ typecheck demo.ts
No type errors.
$ node demo.ts
Your cup: large
Your cup: undefined
TypeScript found no error, because nobody said what cupSize should return. It worked out "text or undefined", and printing undefined is fine as far as it knows. Press Next to follow the returns:
Write : string after the parameters, and every way out must be text:
$ typecheck demo.ts
demo.ts:4:3 - error TS2322: Type 'undefined' is not assignable to type 'string'.
4 return;
~~~~~~
Your turn
Your four tasks are at the top, all in exercise.ts, each with its own comment. Task 1 is the whole file: it is green when typecheck prints No type errors. Dev asks task 4 as an interview question: what a return type promises, and why TypeScript said nothing before you wrote one.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
exercise.ts: no type errors in the whole file
Kabir copied Tapri's billing code straight from the JavaScript app, and under the lab's strict settings it does not compile: typecheck says three parameters implicitly have an any type.
Give every parameter in the file a type (tasks 2 and 3 say which), so typecheck prints No type errors. Typing them any would silence the errors and check nothing. This task is about the whole file, so the error that task 4 shows you must be fixed too.
- Task 2
priceWithGst: two numbers in, a number out
priceWithGst adds GST to a price: priceWithGst(40, 5) is 42 and priceWithGst(100, 18) is 118.
Give both parameters, price and gstPercent, the type number, and give the function the return type number, so a price written as text, like priceWithGst('40', 5), is a type error. That call is the ₹402 bill: JavaScript glued the text and the GST together.
- Task 3
itemCount: only a list of item names
itemCount counts the items in an order: itemCount(['masala chai', 'bun maska']) is 2 and itemCount([]) is 0.
Give items the type string[], a list of text (a plain list, not readonly), so one name on its own, itemCount('masala chai'), and a list of prices, itemCount([40, 25]), are both type errors.
- Task 4 · interview question
Interview: orderLine, a return type finds a bug
orderLine writes one line of the bill: orderLine({ name: 'masala chai', qty: 2, price: 40 }) is '2 x masala chai = ₹80', and orderLine({ name: 'bun maska', qty: 0, price: 30 }) is '0 x bun maska = ₹0'. Right now the second call returns undefined, and the bill prints it.
Give orderLine the return type string, so every way out of it must return text. typecheck then points at Bunty's bug: fix that line so it returns the line for a quantity of 0. Dev will ask what a return type promises, and why TypeScript said nothing before you wrote one.
What you will learn
- Parameter types: bill: number says what a function accepts, and a call that does not fit is an error before anything runs.
- Strict mode: in the lab, a parameter with no type is an error, not a silent any.
- List types: number[] is a list of numbers.
- Return types: : string after the parameters is a promise that TypeScript checks on every return.
More in Why types
Build "Your first types" 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.