繁体   English   中英

如何在取决于可选参数的 TypeScript 输出类型中定义

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

我已经尝试了以下但它不起作用

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

您可以使用条件类型执行此操作:

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

游乐场链接

但更好的解决方案可能是使用重载:

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

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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