Lesson 1 · Unit 06
Unions and narrowing
A value that is one of several types, and how to find out which
What you practise
string | number, literal types,nullandundefinedunderstrict, narrowing withtypeofand===,?.and??, akindfield that tells shapes apart
Try a question from this lesson
Pick one
The type string | number reads "a string or a number". Which line does the compiler reject?
let id: string | number = 7;
id = "A7";
id = true;Correct answer
Line 3
Why
A union widens what a variable may hold, but only to the types it lists. A number is fine, a string is fine, and true is neither. Line 2 would have been an error with a plain number annotation.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Narrowing
A union type lists alternatives. Before you use the value as one of them, prove which one it is.
typeof gives the kind of a value as text: "number", "string", "boolean". Inside the if, the compiler has narrowed id to number. After it, only string is left.
type Id = string | number;
function show(id: Id): string {
if (typeof id === "number") {
return `#${id + 1}`; // number here
}
return id.toUpperCase(); // string here
}
console.log(show(7), show("a7")); // #8 A7Concept
Literal types
A union can list exact values instead of whole types. "left" | "right" allows those two strings and nothing else.
A typo is no longer a string that happens to be wrong. It is a value outside the type, and the compiler catches it before the program runs.
type Dir = "left" | "right";
let d: Dir = "left";
d = "right";
// d = "rihgt";
// rejected: "rihgt" is not a DirConcept
null and undefined
undefined means "nothing was ever put here". null means "empty on purpose". Under strict neither may hide inside a string: the type has to say string | null.
Two shortcuts help. a?.b reads b only if a is there, and gives undefined if not. a ?? b means: use a, unless it is null or undefined, then use b.
const names = ["ada", "bo"];
const hit = names.find((n) => n === "cy");
// hit is string | undefined
console.log(hit?.length); // undefined
console.log(hit ?? "nobody"); // nobody9 more exercises in the app
- 3× multiple choice
- 1× fill the blanks
- 3× type the answer
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.