【问题标题】:Extends generic type with optional properties in TypeScript在 TypeScript 中使用可选属性扩展泛型类型
【发布时间】:2021-02-11 23:38:03
【问题描述】:

我试图扩展一个泛型类型,让函数知道泛型类型可以具有这些属性,但是当我传递一个对象时,它需要这些属性在对象上。

type TWithParams = {
    ignore?: boolean
}
function printList<T extends TWithParams>(items: T[], itemAccessor: (i: T) => string) {
    items.forEach(i => {
        if (!i.ignore) {
            console.log(itemAccessor(i))
        }
    })
}

我应该使用可选参数扩展我传递给函数的所有对象,这有点烦人。

type Fruit = {
    name: string
}
const fruits: Fruit[] = [
    {name: 'Banana'},
    {name: 'Strawberry'},
    {name: 'Apple'},
]

printList(fruits, i => i.name) // this does not work

const fruitsWithIgnore: (Fruit & TWithParams)[] = [
    {name: 'Banana'},
    {name: 'Strawberry'},
    {name: 'Apple'},
]

printList(fruitsWithIgnore, i => i.name) // this works

是否可以在不扩展类型的情况下使第一个函数工作?

Playground

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    你可以这样写printList

    function printList<T>(items: (T & TWithParams)[], itemAccessor: (i: T & TWithParams) => string) {
        items.forEach(i => {
            if (!i.ignore) {
                console.log(itemAccessor(i))
            }
        })
    }
    

    【讨论】:

    • 哦,哇,这比我想象的要简单。我想知道为什么我坚持使用扩展而不是尝试使用联合。好吧没关系,谢谢你的帮助!
    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多