繁体   English   中英

使用 TypeScript 中的可选属性扩展泛型类型

[英]Extends generic type with optional properties in TypeScript

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

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

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

操场

你可以这样写printList

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

暂无
暂无

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

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