typescript · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
keeps your values exactly as you wrote them.
Write let size = "large"; and TypeScript labels the box string, not "large", because a let might change later. That is : an exact literal type grows into its general type. Object properties widen too, even inside a const object, because properties can change.
Add as const after a value and nothing widens. Strings stay literal types and numbers stay exact. Arrays become readonly tuples, and every property becomes readonly. Try to change one and the checker stops you with TS2540.
const loose = { size: "large", sugar: 2 };
const exact = { size: "large", sugar: 2 } as const;
loose.size = "tiny";
console.log(loose.size, exact.size);
const sizes = ["small", "medium", "large"] as const;
console.log(sizes.length, sizes[2]); Think of as const as laminating a card: everyone can read it, nobody can write on it.
guess first
Change a locked order. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const order = { drink: "tea", cups: 2 } as const;
order.cups = 3;
console.log(order.cups);
your turn
Your turn. Order from a fixed menu.
Make the list of sizes exact, so its items fit the size parameter. Then pick a size by its index: 0, 1 or 2.
fix it
The lift will not move. Can you fix it?
- Read the error:
TS2345says astringcannot go where aDirectionis needed. - The property was written as
"up", but object properties widen tostring, andmoveonly takes"up"or"down". - Add
as constafter the closing curly bracket on line 5.
nailed it
your values keep their exact shape now. :D
- Widening turns
"large"intostringwhen a value might change. as constkeeps literals exact and makes everythingreadonly.- Use it for fixed lists of options and settings.
new words in your collection
- widening
- as const
This lesson isn’t saved. A free account remembers every lesson you finish.