Federico Moretti
Federico Moretti

Reputation: 89

Extends generic type with optional properties in TypeScript

I'm trying to extend a generic type to let the function know that the generic type could have those properties, but then when I pass an object it requires those properties to be on the object.

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))
        }
    })
}

I should have to extends all the object that I pass to the function with the optional params, and it's kinda annoying.

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

Is it possible to make the first function works without extending the type?

Playground

Upvotes: 1

Views: 1465

Answers (1)

St&#233;phane Veyret
St&#233;phane Veyret

Reputation: 1991

You can write the printList like this:

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

Upvotes: 2

Related Questions