#Deep inferring in lookup

5 messages · Page 1 of 1 (latest)

hot condor
#

Hi, I'm relatively new to typescript. I'm having trouble trying to think of a way to force typescript to limit the possible types it accepts for my Node variable from the previously given NodeCategory in the string, and then continue that pattern even further in. Here's the code:

type MagicNodeCategory = 'Celestial' | 'Elemental' | 'Nature' | 'Shadow' | 'Support'
type CelestialNodeCategory = 'Holy' | 'Unholy'
type ElementalNodeCategory = 'Wind' | 'Fire' | 'Water' | 'Earth'

type Node = `${NodeCategory}-${CelestialNodeCategory | ElementalNodeCategory}`

For example, I want Typescript to recognize that 'Celestial-Holy' and 'Celestial-Unholy' are valid options but 'Celestial-Wind' is not.

obsidian glacier
#
type Node =
    | `Celestial-${CelestialNodeCategory}`
    | `Elemental-${ElementalNodeCategory}`
    // ...
#

You can also rewrite it into a map:

type MagicNodeCategories = {
    Celestial: 'Holy' | 'Unholy'
    Elemental: 'Wind' | 'Fire' | 'Water' | 'Earth'
}

type MagicNodeCategory = keyof MagicNodeCategories

type MagicNode = {
    [K in MagicNodeCategory]: `${K}-${MagicNodeCategories[K]}`
}[MagicNodeCategory]
#

!ts MagicNodeCategory MagicNode

obsidian loomBOT
#
type MagicNodeCategory = keyof MagicNodeCategories /* 6:6, 9:11, 10:3 */``````ts
type MagicNode = "Celestial-Holy" | "Celestial-Unholy" | "Elemental-Wind" | "Elemental-Fire" | "Elemental-Water" | "Elemental-Earth" /* 8:6 */```