Derive Types

Loading "Derive Types"
πŸ‘¨β€πŸ’Ό You may have noticed that we're duplicating our operators of +, -, *, and /. Any time we want to add a new operator, we have to add it in two places and if we miss one then we could either have a runtime error, or users won't be able to use our new operator at all.
It would be better if we could have the compiler let us know we missed one (foreshadowing... look forward to that in an upcoming step) or just derive the possible operators.
To do this, you need to know about two TypeScript keywords: typeof and keyof. Technically typeof is a JavaScript feature, but TypeScript builds on top of this and will get you the TypeScript type for the given variable. So if you say:
const user = { name: 'kody', isCute: true }
type User = typeof user
// type User = { name: string; isCute: boolean; }
And then you can use keyof to get a union-ed type of strings of all the keys in a given type:
type UserKeys = keyof User
// type UserKeys = "name" | "isCute"
πŸ“œ Learn more about TypeScript's typeof operator and keyof operator.
With that, try and derive the type of the CalculatorProps['operator'] so you don't have to repeat yourself.
Login to get access to the exclusive discord channel.
  • βš›οΈFundamentals
    First Four Exercises are Free!
    Kent C. Dodds β—† πŸš€πŸ†πŸŒŒ:
    To make sure this shows up in the fundamentals thread. Isn't it exciting the first four exercises of...
    1 Β· 4 days ago
  • General
    Welcome to EpicReact.dev! Say Hello πŸ‘‹
    Kent C. Dodds β—† πŸš€πŸ†πŸŒŒ:
    Welcome to the first of many posts in the EpicReact.dev channel! Take a moment to introduce yourself...
    0 Β· 4 days ago