Francisco Ramos
Francisco Ramos

Reputation: 523

Type conditioned to a Generic type

I was wondering if something like this is possible in TypeScript:

type Something = {...}

interface A extends Something {...}
interface B extends Something {...}

interface MyInterface<T extends Something> {
    method(): T
    anotherMethod(): number | number[]
}

The type returned by anotherMethod() depends on the generic, meaning:

E.g.

const myObjA: MyInterface<A> = {}
myObjA.anotherMethod() // ==> returns a number

const myObjB: MyInterface<B> = {}
myObjB.anotherMethod() // ==> returns an array

Does the question make sense?

Thanks in advance, Fran

Upvotes: 0

Views: 40

Answers (1)

bugs
bugs

Reputation: 15313

Sure thing, you can use conditional types for that.

interface MyInterface<T extends Something> {
    method(): T
    anotherMethod(): T extends A ? number : number[]
}

declare const myObjA: MyInterface<A>
const a = myObjA.anotherMethod() // number

declare const myObjB: MyInterface<B>
const b = myObjB.anotherMethod() // number[]

Upvotes: 2

Related Questions