typescript · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A lets a value be one of several types.
Sometimes a value can be one type or another. A locker might be numbered 12 or named "A3". A union type lists the choices with | between them, read as or: string | number.
You have met one already. prompt gives back string | null: a string, or nothing at all. That is why you needed ?? to get a plain string out.
The box may hold any type in the union, and nothing else. Try to put true in a string | number box and the checker says TS2322.
let locker: string | number = 12;
console.log(`Locker ${locker}`);
locker = "A3";
console.log(`Locker ${locker}`);
type Id = string | number;
const ids: Id[] = [7, "B2", 15];
console.log(ids); A type alias is a handy way to name a union you use often, like type Id = string | number;.
guess first
Which values fit the union? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Answer = string | number;
const answers: Answer[] = ["yes", 42];
answers.push(false);
console.log(answers.length);
your turn
Your turn. Store a score that can be a word.
A quiz score is a number, or the word "absent" when someone missed the quiz. Fill in the two types of the union, then put one of each into the array.
fix it
Some houses have names, not numbers. Fix it!
- Read the error:
TS2322: Type 'string' is not assignable to type 'number'.Which line is it about? - The box is labelled
number, but line 3 puts a name in it. The label needs to allow both. - Change the label on line 1 to
number | string, then press run.
nailed it
your boxes can hold this or that. :D
- A union type lists the types a value may have, with
|. string | nullfrompromptwas a union all along.- Anything outside the union is stopped by the checker.
new words in your collection
- union type
This lesson isn’t saved. A free account remembers every lesson you finish.