Looking to create a new type based on the keys of another object in TypeScript.
Successfully achieved this through type inference. However, using an explicit type Record<string, something>
results in keyof
returning string
instead of a union of the actual keys used.
View TypeScript Playground GIF
Check out this example code:
type FileType = "image" | "video" | "document";
type FileTypeList = Record<string, FileType>
const inferedFileList = {
a: "image",
b: "video",
c: "document"
}
//type files = "a" | "b" | "c"
type files = keyof typeof inferedFileList;
const explicitelyTypedList : FileTypeList = {
a: "image",
b: "video",
c: "document"
}
//type typedFiles = string
type typedFiles = keyof typeof explicitelyTypedList;
Access Relevant TypeScript Playground
Is it possible to use explicit typing like Record<string, something>
and still obtain a union type with keyof
? Perhaps there is a keyword that functions similarly to typeof
, but utilizes the shape of an object instead of its declared type. Does TypeScript offer such functionality?