#Why does this type not work?
20 messages · Page 1 of 1 (latest)
Equipment['subWeaponType'] is just SubWeaponTypes, so that conditional always evaluates to 0.
Also screenshot is not advised.
!:screenshot
`!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.
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
type Equipment = {
subWeaponType: "knuckle";
subWeaponDEF: 0;
} | {
subWeaponType: "arrow";
subWeaponDEF: 0;
} | {
subWeaponType: "shield";
subWeaponDEF: number;
} | {
subWeaponType: "dagger";
subWeaponDEF: 0;
} | {
...;
} /* 3:6 */```
what is a DU?
!hb discriminated union
Get Started / TypeScript for Functional Programmers
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
type Equipment = {
subWeaponType: "knuckle";
subWeaponDEF: 0;
} | {
subWeaponType: "arrow";
subWeaponDEF: 0;
} | {
subWeaponType: "shield";
subWeaponDEF: number;
} | {
subWeaponType: "dagger";
subWeaponDEF: 0;
} | {
...;
} /* 11:6 */```
i see