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
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
CLICK HERE to find out more related problems solutions.