How to describe the type of a dictionary in typescript more efficient, than the solution below?
type DictEntry = { [key: string]: string }
type UploadDict = { [key: string]: DictEntry }
const UPLOAD_TYPE_DICT: UploadDict = {
JPG: {
label: "jpg",
type: "image/jpeg",
},
PNG: {
label: "png",
type: "image/png",
},
}
CodePudding user response:
I can see some type patterns from your example, so I'd propose using enum
to keep file types and using DictEntry
to keep label
and type
as strongly-typed properties
You can check the playground here
enum FileType {
JPG,
PNG
}
type DictEntry = { label: string, type: string }
type UploadDict = { [K in keyof typeof FileType]: DictEntry }
const UPLOAD_TYPE_DICT: UploadDict = {
JPG: {
label: "jpg",
type: "image/jpeg",
},
PNG: {
label: "png",
type: "image/png",
},
}
CodePudding user response:
If you mean a cleaner syntax with more efficiently use Record
.
type DictEntry = Record<string, string>
type UploadDict = Record<string, DictEntry>
const UPLOAD_TYPE_DICT: UploadDict = {
JPG: {
label: "jpg",
type: "image/jpeg",
},
PNG: {
label: "png",
type: "image/png",
},
}