1

I have different types with numeric id properties, and I want to make sure I don't pass the wrong id into functions (the numbers are only unique within the type).

Is there a way to make typescript complain if I pass a wrong id type?

type AId = number
type A = {id: AId}
type BId = number
type B = {id: BId}

const fnA = (id: AId) => {}

const b: BId = {id: 5}

// I'd like for this to give a type error (not a runtime check)
fnA(b.id)

This code does not give a type warning. Can TS be told that only AId is the correct parameter type, and not just any type that is number?

w00t
  • 17,944
  • 8
  • 54
  • 62
  • 1
    1. This line produces an error because of your typo: `Property 'id' does not exist on type 'number'.(2339)` 2. What you are trying to is not possible since TypeScript is structurally typed. Type `A` and `B` are identical to the compiler. – Tobias S. Jun 08 '22 at 21:37
  • 2
    (The term to search for here is "nominal typing", which differs from the "structural typing" that TypeScript uses by default.) – Jeff Bowman Jun 08 '22 at 21:38
  • @TobiasS. Turns out that what I want is nominal typing and it's possible with `type AId = number & {T?: 'A'}`. The literal T types will clash. Thanks @JeffBowman! – w00t Jun 09 '22 at 01:55

0 Answers0