【问题标题】:TypeScript with the Rest Operator binding element x implicitly has an 'any' type带有 Rest Operator 绑定元素 x 的 TypeScript 隐式具有“任何”类型
【发布时间】:2021-10-04 09:44:35
【问题描述】:

我有以下一行 TypeScript 代码:

const removeType = ({ type, ...rest }) => rest;

这是一个从传入的rest 对象中删除type 属性的函数。 See here.

我收到以下错误:

绑定元素 'type' 隐含地具有 'any' 类型。

如何消除错误?这可能是一个 linting 错误,但如果可能的话,我想摆脱它。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你可以这样输入:

    const removeType = <T extends { type: unknown }>({ type, ...rest }: T) => rest;
    

    现在:

    const x = removeType({ type: 1, somethingElse: "hello" })
    
    console.log(x.somethingElse);
    // console.log(x.type) // error!
    

    Playground Link

    【讨论】:

      【解决方案2】:

      你也可以推断rest obj的类型

      const removeType = <Rest,>({ type, ...rest }: { type: unknown } & Rest) => rest;
      
      const x = removeType({ type: 'div', name: 'John' })
      x.name // ok
      x.type // error
      
      

      Playground

      这里有通用的正确类型的解决方案:

      const removeProperty = <Obj, Prop extends keyof Obj>(obj: Obj, prop: Prop) => {
        const { [prop]: _, ...rest } = obj;
        return rest
      }
      

      鼠标悬停在函数名上,你会看到返回值的类型:Omit&lt;Obj, Prop&gt;

      您可以在我的blog 中找到更多示例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-06
        • 2021-11-11
        • 2020-04-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-13
        • 2021-05-15
        相关资源
        最近更新 更多