ThomasReggi
ThomasReggi

Reputation: 59575

Type function which passes through spread object props

Below I have a function spreadProps which takes a prop age from the first argument, and adds 10 to it, returning age and ageProps. However I also spread all the rest of the props, and would like to return those as well. How do I do this? If I pass in an extra prop, say name how can I also have the function's return type be aware that was passed in and is returned?

const spreadProps = (
    { age, ...props}:
    { age: number, props?: any }
): { age: number, agePlus: number } => {
    const agePlus = age + 10
    return { age, agePlus, ...props }
}

const x = spreadProps({ age: 12, name: 'Tom '})

console.log(x.name)

Upvotes: 1

Views: 52

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

You need a generic type argument to capture the input type. This should work:

const spreadProps = <T extends { age: number }>(
    { age, ...props }: T
) => {
    const agePlus = age + 10
    return { age, agePlus, ...props }
}

const x = spreadProps({ age: 12, name: 'Tom ' })

console.log(x.name)

Playground Link

Upvotes: 1

Related Questions