I am attempting to create a unique form of enumeration, where each key in the enum is associated with specific data whose type I want to define.
For example:
const Seasons = {
winter: { temperature: 5, startMonth: "December" },
spring: { temperature: 20, startMonth: "March" },
summer: { temperature: 30, startMonth: "June" },
fall: { temperature: 15, startMonth: "September" },
} as const
This setup allows me to utilize features like:
type Season = keyof typeof Seasons // "winter" | "spring" | "summer" | "fall"
and even implement a type guard such as
function isSeason(s: string): s is Season {
return Object.keys(Seasons).includes(s)
}
However, I face an issue in ensuring that all season definitions adhere to a specified type. When I try:
type SeasonData = typeof Seasons[Season]
SeasonData
becomes a union of all definition types, regardless of their shape.
So, I aim to find a concise and efficient way to define something similar to:
const Seasons: EnumWith<{temperature: number, startMonth: string}> = ... // as previously shown
^^^^^^^^ <- yet to be determined!
Specifically, I prefer to avoid duplicating the list of seasons in any other structure (like interface or array) and directly infer the type Season
from the object definition (although open to alternatives!).
Any suggestions on how to achieve this?