how do i define a typescript output type which depends on the optional parameter?

You can do this with conditional types:

export class Product {
    static getItems: <T extends string | undefined = undefined>(itemId?: T) => T extends undefined ? Item[] : Item = null!
}

// Test Cases
const item: Item = Product.getItems('id') // returns Item because parameter is present

const item2: Item[] = Product.getItems() // returns Item[] because parameter itemId is omitted

Playground Link

But a better solution would probably be to use overloads:

type Item = { p: string }
export class Product {
    static getItems(): Item[]
    static getItems(itemId: string): Item
    static getItems(itemId?: string): Item | Item[] {
      return null!
    }
}

// Test Cases
const item: Item = Product.getItems('id') // should return Item because parameter is present

const item2: Item[] = Product.getItems() // should return Item[] because parameter itemId is omitted

Playground Link

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top