TypeScript: keyof reference
2 December 2022 (Updated 7 April 2024)
On this page
In a nutshell
TypeScript’s keyof
operator takes an object type and produces a string or numeric literal union of its keys.
This means you can declare a type like:
type SomeObjectType = {1: string, 2: string}
Then use keyof
to create another derived type:
type DerivedType = keyof SomeObjectType
DerivedType
will now be equal to the numeric literal union of SomeObjectType
‘s keys 1 | 2
(1
and 2
are the keys of SomeObjectType
). So if you do something like:
const foo: DerivedType = 3
You’ll get the error:
Type '3' is not assignable to type 'keyof SomeObjectType'.(2322)
Because 3
is not assignable to 1 | 2
.
But if you do:
const foo: DerivedType = 1
Then all is good because 1
is assignable to 1 | 2
.
Try this example in the TS Playground.
Sources
Tagged:
TypeScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment