how to prevent TS interpreter from losing track of custom type (as subtype of string)?

2 weeks ago 17
ARTICLE AD BOX

Here's a simplified version of what I'm trying to do

type UnitId = string interface Unit { id: UnitId name: string } const x: Unit = { id: 'foo', name: 'bar' } console.log(x.id)

when I highlight x.id in VS code, it shows (property) Unit.id: string

The type UnitId is "lost", I'd like it to say (property) Unit.id: UnitId

Is there a way to force that ?

To add more context : UnitId is supposed to be a subset of string. The units comes from an API, I cannot define UnitId as `"id1" | "id2" | ...`

I've got a lot of other object using that type, ex :

type StatsByUnitId = { [index: UnitId]: Stats }

and in theory statsByUnitId['randomStringNotDefinedAsUnitId'] should show a TS error

but statsByUnitId[x.id] should not

Read Entire Article