【问题标题】:Type function which passes through spread object props通过传播对象道具的类型函数
【发布时间】:2019-11-13 05:39:05
【问题描述】:

下面我有一个函数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)

【问题讨论】:

    标签: typescript arguments return-type


    【解决方案1】:

    您需要一个泛型类型参数来捕获输入类型。这应该有效:

    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

    【讨论】:

    • 这真的很酷,谢谢。但是我遇到了麻烦,&lt;T extends { value: string }&gt;({ value: v, ...props }: T = {}) 试图分配一个默认值以使整个参数成为可选的。有什么想法吗?
    • @ThomasReggi 通常将值分配给作为类型参数键入的内容并不安全,因为T 可能需要道具。您可以使用类型断言{ age, ...props }: T = {} as T,但不确定结果是否正是您想要的。
    • 这是我正在尝试做的完整示例。 stackoverflow.com/questions/58827771/…
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 2014-10-07
    相关资源
    最近更新 更多