简体   繁体   中英

How to define in TypeScript output type which depends on optional parameter

I have tried the following but it doesn't work

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM