typescript · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Turn a value into a type with typeof.
You met typeof in Level 1: at runtime it answers with text like "number". Placed where a type belongs, it does something else. That spot is a : after a colon, inside <>, or after type Name =.
In a type position, typeof defaults is a . It asks the checker for the type of the value called defaults. Write the value once and copy its type, so the two can never drift apart. Change the value and the type follows.
const defaults = { volume: 7, theme: "dark", subtitles: false };
type Settings = typeof defaults;
function describe(settings: Settings): string {
return `Volume ${settings.volume}, ${settings.theme} theme`;
}
console.log(typeof defaults);
console.log(describe({ volume: 3, theme: "light", subtitles: true })); Line 2 copies a type and line 6 asks a runtime question. Same word, two jobs.
guess first
A rival player joins. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const player = { name: "Ada", lives: 3 };
type Player = typeof player;
const rival: Player = { name: "Grace", lives: "three" };
console.log(rival.name);
your turn
Your turn. Copy the type of an order.
Turn firstOrder into a type with a type query, then fill in an item and a quantity for the next order.
fix it
The pet maker will not run. Can you fix it?
- Read the error:
TS2749saysblankPetis a value, but it is being used as a type. - A value cannot sit in a type position on its own. You need a type query to copy its type.
- On line 2, change the return type to
typeof blankPet, then run.
nailed it
you can copy types straight from values. :D
- In a type position,
typeof valuecopies that value's type. - At runtime,
typeofstill answers with text like"object". - Write data once and let the type follow it.
new words in your collection
- type position
- type query
This lesson isn’t saved. A free account remembers every lesson you finish.