Derive Types
Loading "Derive Types"
Run locally for transcripts
π¨βπΌ 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.