typescript - 为什么 Typescript 类型检查器对这种未指定的类型感到不安?

标签 typescript compiler-errors visual-studio-code

我有一个 react 组件,其 Prop

  • 需要序列化/存储,
  • 包含函数

  • 我的存储实用程序不喜欢存储函数,我不需要存储的函数。所以我写了一个函数,它返回一个没有函数组件的 props 对象的副本:
    /**
     * Removes functions from the components props, so that the props can be pouched
     */
    strippedProps(): Object {
        let strippedProps: Object = {};
    
        Object.keys(this.props).forEach((key) => {
            let prop: any = this.props[key];
    
            if (typeof (prop) != 'function') {
                strippedProps[key] = prop;
            }
        })
    
        return strippedProps;
    }
    

    TS 愤怒地强调,我对此感到困惑,因为 prop这里特意声明为any .

    enter image description here

    为什么 TS 对这里的第一个错误(警告)不满意?为了让编译器满意并满足生成这个动态对象的需要,我该如何重构?

    最佳答案

    this.props 上缺少索引签名' 类型。

    Indexable Types

    Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example:


    要修复它,您需要告诉 Typescript this.props ' 对象类型有字符串作为键:
    interface QuestionViewProps { 
       ... your definition,
       [key: string]: myType,
    }
    

    第二种选择是通过 "suppressImplicitAnyIndexErrors": true 抑制警告。 .

    第三个选项是强制转换为 ,这将不再是类型安全的:
     let prop: any = (<any>this.props)[key];
    

    关于typescript - 为什么 Typescript 类型检查器对这种未指定的类型感到不安?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44460453/

    相关文章:

    javascript - 从状态数组中删除对象

    html - 如何使 ng2-charts 垂直条形图水平滚动?

    c - 错误:warning comparison between pointer and integer

    visual-studio-code - Visual Studio Code - 在 Windows 上的 'select default shell' 列表中添加选项?

    javascript - Angular 8 使用 NgRx 从 http 设置状态

    typescript - Vue TSX - 如何告诉 Typescript 在可重用组件中允许使用 HTML 属性?

    java - 为什么Java中Integer对象的计数速度比int慢

    scala - 编译错误Scala项目

    c++ - 使用gdb调试时如何解决VS Code中: "launch : program "executable. out"does not exist"

    git - 您的存储库没有配置为推送到的 Remote