Online sign-up forms check what goes into each field. The name field takes letters, the age field only takes numbers, and a checkbox can only be ticked or not. Enter "seventeen" in the age field, and the form refuses it.
Types in TypeScript work like the rules of those form fields. Variables and parameters are the fields, and a type names the kind of value that may go into each one. When a value doesn't fit, TypeScript refuses it with an error message, like the form that refuses "seventeen". The three types you'll use most: string for text, number for numbers, and boolean for true or false.
The three basic types
Here are those three types, one on each variable:
let name: string = "Budi";
let score: number = 90;
let passed: boolean = true;
stringis for any text inside quotes:"Budi",'Budi', or a template literal`Budi`.numberis for every number, whole or decimal:90,3.14,-5. There's no separate type for whole numbers.booleanhas only two values:trueandfalse, without quotes.
Inference: TypeScript guesses the type
The code below has no type annotation at all. Before you read further, guess: does TypeScript reject the second line, or accept it?
let score = 90;
score = "95";
The second line is still rejected:
Type 'string' is not assignable to type 'number'. ts(2322)
When a variable gets a value as it's created, TypeScript guesses its type from that value. Guessing the type from the value like this is called inference. The first value of score is 90, so score has the type number. Hover over score in VS Code and you'll see let score: number. So you can skip the type annotation on a variable when its value already makes the type clear.
The table below shows what TypeScript's check says for a few pairs of lines. You can try exactly the same pairs in the Lab. The any in the last row is covered below.
| Line 1 | Line 2 | What TypeScript says |
|---|---|---|
let score = 90; |
score = 95; |
no error |
let score = 90; |
score = "95"; |
Type 'string' is not assignable to type 'number'. |
let score: number = 90; |
score = true; |
Type 'boolean' is not assignable to type 'number'. |
let score: any = 90; |
score = "95"; |
no error |
Function parameters are different. TypeScript can't guess what value will be sent to the function later. A parameter without a type is rejected with the error Parameter 'name' implicitly has an 'any' type. ts(7006). It means: without a type, name is treated as having the type any (a type that accepts any value). So parameters always get a type.
Types on function parameters and return values
The function greet below has types on its parameter and on the value it returns:
function greet(name: string): string {
return "Hello, " + name + "!";
}
console.log(greet("Budi")); // Hello, Budi!
console.log(greet("Ani")); // Hello, Ani!
name: string: the parameternamehas to hold text.): stringafter the closing parenthesis is the return type, which is the type of the value the function returns. Here,greethas to return text."Hello, " + name + "!"joins three pieces of text. The template literal`Hello, ${name}!`gives the same result.greet(17)is rejected:Argument of type 'number' is not assignable to parameter of type 'string'. ts(2345).
TypeScript checks the return type too. If the function's body is still empty, or only holds a console.log, TypeScript reports this error:
A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value. ts(2355)
It means: the return type written for this function isn't undefined, void or any (void and any are covered below). So this function must return a value with return.
any and unknown
any and unknown both accept every kind of value. The difference is in what you're allowed to do with the value afterwards. Look at the code below. The third line has toFixed(1), a number method (a function that belongs to a number value) that writes a number with one digit after the decimal point: 95 becomes "95.0".
let score: any = 90;
score = "95";
console.log(score.toFixed(1));
- With
any, TypeScript reports no error at all. The error only appears when the code runs:TypeError: score.toFixed is not a function, becausescorenow holds the text"95", and text has notoFixed.anydisables checking, so avoidany. - Change
anytounknown, and TypeScript rejects the third line before the code runs:'score' is of type 'unknown'. ts(18046). You have to make sure what kind of value it holds first, for example withtypeof:
let score: unknown = 90;
score = "95";
if (typeof score === "number") {
console.log(score.toFixed(1));
}
Inside the if, TypeScript knows score is definitely a number. Checking the kind of value like this is covered in more depth in the Type Narrowing lesson.
The place where you meet unknown most often is catch. In strict mode (stricter type checking), the error that catch receives has the type unknown. The reason: throw can throw any value, not only an Error. The code below uses instanceof, which checks whether err is an Error:
try {
JSON.parse("{broken");
} catch (err) {
if (err instanceof Error) {
console.log(err.message);
}
}
It prints Expected property name or '}' in JSON at position 1 (line 1 column 2). Without if (err instanceof Error), err.message is rejected: 'err' is of type 'unknown'. ts(18046).
null, undefined, and void
undefinedmeans there's no value yet,nullmeans it was emptied on purpose.strictmode is TypeScript's default today (covered in the tsconfig lesson). In that mode,let name: string = null;is rejected:Type 'null' is not assignable to type 'string'. ts(2322). How to allow "text or null" is covered in the Union & Literal lesson.voidis the return type of a function that doesn't return anything:
function logMessage(message: string): void {
console.log(message);
}
⚠️ A forgotten return, and an any that hides the bug
- Forgetting
return. In the exercise, the body ofgreetin the starter code is still empty. Sogreetreturnsundefined, and TypeScript reports the errorts(2355).console.logisn't the same asreturn: what's graded is the value that comes back. - A fixed sentence.
return "Hello, Budi!";fits Budi. But the exercise also testsgreet("Ani"), which must give"Hello, Ani!". Use the parameternameinstead of writing the name Budi directly into the sentence. - The comma, the space and the exclamation mark. The result must be exactly
Hello, Budi!: a comma and a space afterHello, an exclamation mark at the end. - Using
anyto make an error go away. The error is only hidden. The bug is still there, and it appears when the code runs. If the type isn't clear yet, useunknown, then check it withtypeof.
TL;DR: A type names the kind of value a variable or parameter holds: string for text, number for every number, boolean for true/false. A variable that gets a value right away doesn't need a type annotation, because TypeScript guesses its type from that value. Guessing the type like this is called inference: let score = 90 is already a number. Parameters always get a type. The return type, which is the type of the value the function returns, goes after the closing parenthesis: function greet(name: string): string { return "Hello, " + name + "!"; }. A function whose return type isn't void (the type for a function that returns nothing) must have a return. any and unknown both accept any value: any disables checking, while unknown has to be checked before it's used.
⚡ TypeScript guesses the type
Write:
let score = 90;
score = "95";
Guess first: this code has no type annotation at all. Does TypeScript reject the second line, or accept it?
Rejected: Type 'string' is not assignable to type 'number'. TypeScript guessed that score is a number from its first value, 90. So the text "95" can't go in.
Meaning: Guessing the type from the first value is called inference. A variable that gets a value right away can go without a type annotation. Function parameters are different: TypeScript can't guess what value will be sent to the function later. So parameters always get a type.
⚡ Types on parameters and the return value
Write:
function greet(name: string): string {
return "Hello, " + name + "!";
}
console.log(greet("Budi")); // Hello, Budi!
Meaning: name: string means the parameter name has to hold text. ): string is the return type, the type of the value the function returns: text, here. TypeScript checks that return type. Without a return, TypeScript reports the error ts(2355), and console.log can't replace return.
In the exercise, the result has to be exactly Hello, Budi!, with the comma, the space and the exclamation mark. Use the name parameter instead of writing the name Budi directly into the sentence.
⚡ any stays quiet, unknown wants a check
Write:
let score: unknown = 90;
score = "95";
if (typeof score === "number") {
console.log(score.toFixed(1));
}
Meaning: any and unknown are types that accept any value. If you change unknown in this code to any, TypeScript doesn't check how score is used at all. So score.toFixed(1) is accepted even without the if. Then the code fails with an error when it runs, because score now holds the text "95": toFixed is a number method, and text doesn't have it. With unknown, TypeScript rejects score.toFixed(1) until you make sure what kind of value it holds, for example with typeof.