I have a few simple types:
export const structureTypes = ["atom", "molecule"] as const
export type Structure = typeof structureTypes[number]
export const atomTypes = [
"hydrogen",
"oxygen",
"argon",
] as const
export const moleculeTypes = [
"water",
"methane",
] as const
export type AtomType = typeof atomTypes[number]
export type MoleculeType = typeof moleculeTypes[number]
I would like to be able to use these to constrain the possible inputs of an object that holds the IDs of each type:
export type StructureIdCache = {
[key in Structure as string]: {
[key in AtomType | MoleculeType]: string
}
}
This works, but allowing AtomType | MoleculeType on the 2nd level allows me to use "water" as a key when the 1st level key is "atom" which is invalid. How can I modify the types to allow input of only allowable names in the 2nd level of the object?
I have tried creating a conditional type:
export type StructureType<T> = T extends Atom ? AtomType : MoleculeType
This works for creating specific types:
type AtomTypeNames = StructureType<Atom>
type MoleculeTypeNames = StructureType<Molecule>
But does not allow me to constrain the inputs for a function:
export const getTypeId = async (
c: Context,
type: Structure,
name: StructureType<typeof type> // <-- this should restrict name inputs but does not
): Promise<string> => {
// do something
}
How can I restrict the valid inputs for name, based on the value of the string passed to type?