Search code examples
typescript-eslint

Unsafe assignment of any value trying to transform properties on an object


I have something like this snippet:

function transformIt(value: any): any {
  ...
}

let foo: any = ...
if (typeof foo === 'object') {
  for (const property in value) {
    foo[property] = transformIt(foo[property])
  }
}

When I run eslint on this, it complains that there's an unsafe assignment of an any value but I can't figure out how to make it happy. Would appreciate any insight on this.


Solution

  • How to check if type has index signature at runtime has the answer. Thought I tried that on my own, but seems to work now.

    function hasIndexSignature(v: any): v is {[index: string]: any} {
      return typeof v === 'object'
    }
    
    let foo: any = ...
    if (hasIndexSignature(foo)) {
      for (const property in value) {
        foo[property] = transformIt(foo[property])
      }
    }