通过传播对象道具的类型函数

下面,我有一个函数spreadProps,该函数从第一个参数中取一个道具age,并将其加10,返回ageageProps。但是,我还散布了所有其他道具,并希望将它们也归还。我该怎么做呢?如果我传递了一个额外的道具,请说name,我又如何让函数的返回类型知道传递过来并返回了?

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)
yyuuzzjj 回答:通过传播对象道具的类型函数

您需要一个通用类型参数来捕获输入类型。这应该起作用:

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

本文链接:https://www.f2er.com/3114148.html

大家都在问