Home > Enterprise >  typescript interface with function returning different types
typescript interface with function returning different types

Time:06-15

Learning typescript and currently developing the following structure

type AModel {
    propA: string
}

type BModel {
    propB: string
}

class AController {
    payload():<AModel> {}
}

class BController {
    payload():<BModel> {}
}

Each controller must implement a payload function which returns their specific payload type. So I want something like this:

interface Payload {
    payload():<T>
}

class AController implements Payload {
    payload():<AModel> {}
}

class BController() implements Payload {
    payload():<BModel> {}
}

I'm assuming that the only way to define T is via a union type of all the different models that could be returned - or is there a better way?

CodePudding user response:

You were close to the right path. By using generics you can achieve what you want:

Check the code in playground

interface Payload<T> {
  payload(): T;
}

interface AModel {
  propA: string
}

class AController implements Payload<AModel> {
    payload() {
      return { propA: 'someValue' }
    }
}

CodePudding user response:

It depends on how free you want implementations of Payload to be.

If Payload can't only hold very specific types, then you should declare a union of what those are.

But, if Payload doesn't care what it holds, then I think you want this:

interface Payload {
    payload(): unknown
}

class AController implements Payload {
    payload(): AModel {
        return { propA: 'a' }
    }
}

class BController implements Payload {
    payload(): BModel {
        return { propB: 'b' }
    }
}

new AController().payload().propA // works

Typescript is smart enough to know that your class returned a subtype of what's declared in the Payload interface, and will use that more specific type if it can.

Playground

  • Related