#Why does this type not work?

20 messages · Page 1 of 1 (latest)

green yarrow
#

Any ideas on the given snippet? I would like this to not cause a type error

timber phoenix
#

Equipment['subWeaponType'] is just SubWeaponTypes, so that conditional always evaluates to 0.

#

Also screenshot is not advised.

#

!:screenshot

sage pollenBOT
#
retsam19#0
`!retsam19:screenshot`:

Rather than screenshots, please provide either code formatted as:

```ts
// code here
```
Or even better, as an example on the Typescript playground https://www.typescriptlang.org/play that is as simple as possible and reproduces the issue. This makes it easier to help you and increases the chances of getting an answer.

green yarrow
#

alright

#

thanks

timber phoenix
#

There are a few ways to do what you want

#

All involves making Equipment into a DU.

#
type SubWeaponType = 'knuckle' | 'arrow' | 'shield' | 'dagger' | 'none'

type Equipment = {
    [T in SubWeaponType]: {
        subWeaponType: T
        subWeaponDEF: T extends 'shield' ? number : 0
    }
}[SubWeaponType]
#

!ts Equipment

sage pollenBOT
#
type Equipment = {
    subWeaponType: "knuckle";
    subWeaponDEF: 0;
} | {
    subWeaponType: "arrow";
    subWeaponDEF: 0;
} | {
    subWeaponType: "shield";
    subWeaponDEF: number;
} | {
    subWeaponType: "dagger";
    subWeaponDEF: 0;
} | {
    ...;
} /* 3:6 */```
green yarrow
#

what is a DU?

timber phoenix
#

!hb discriminated union

sage pollenBOT
timber phoenix
#

If you have more complex mapping than "shield = number, others = 0" you can use a proper map to generate the DU.

#
type DefMap = {
    knuckle: 0
    arrow: 0
    shield: number
    dagger: 0
    none: 0
}

type SubWeaponType = keyof DefMap

type Equipment = {
    [T in keyof DefMap]: {
        subWeaponType: T
        subWeaponDEF: DefMap[T]
    }
}[keyof DefMap]
#

!ts Equipment

sage pollenBOT
#
type Equipment = {
    subWeaponType: "knuckle";
    subWeaponDEF: 0;
} | {
    subWeaponType: "arrow";
    subWeaponDEF: 0;
} | {
    subWeaponType: "shield";
    subWeaponDEF: number;
} | {
    subWeaponType: "dagger";
    subWeaponDEF: 0;
} | {
    ...;
} /* 11:6 */```
green yarrow
#

i see