0

I have a custom interface like this:

interface Pointer<T> {
  id: string
}

id is a pointer to other data structures, but the id field doesn't contain information about which data structure it is pointing to.

Ideally, I would be able to type the Pointer class as to which data structure the Pointer is pointing to, so that I don't accidentally confuse Pointers. For example:

function getBarPointer(): Pointer<Bar> {
  return { 'id': 'abc123' }
}

function getBazPointer(): Pointer<Baz> {
  return { 'id': 'xyz789' }
}

function useBarPointer(p: Pointer<Bar>): void {
  doSomethingWithP(p)
}

This would allow me to make sure I'm passing in the right Pointers at the type checking stage, while also letting me create functions that operate on specific kinds of pointers.

Is this possible? Or in general is there a way to tell typescript to differentiate types that are ostensibly the same?

Right now, as written, typescript just ignores the passed in type to Pointer.

theahura
  • 353
  • 2
  • 19
  • 1
    The general pattern is branded types: https://stackoverflow.com/questions/49260143/how-do-you-emulate-nominal-typing-in-typescript/49260286#49260286 Note that in your specific case, if you don't assign the generic type parameter T to anything on the object, it will *immediately* be lost with no way to get it back later. You'd need to incorporate it into the brand somehow – y2bd May 14 '22 at 20:15
  • Thanks, that (and the article linked on that answer: https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/) helps tremendously – theahura May 14 '22 at 20:27

0 Answers0