Newbyte
Newbyte

Reputation: 3240

Element implicitly has an 'any' type because type '{}' has no index signature error when using object originating from fetched JSON

I'm trying to compile my TypeScript code to JavaScript, but in doing so I get a bunch of errors saying Element implicitly has an 'any' type because type '{}' has no index signature. There occur when I access an object originating from JSON fetched via fetch() and the noImplicitAny compiler option is set to true.

Here is some sample code that triggers the issue on compile:

index.js:

class Foobar {
    constructor(data: object) {
        console.log(data[0].mapScale);
    }
}

getMapObject()
    .then(function(data) {
        console.log(data);
        new Foobar(data);
    });

function getMapObject() {
    return fetch("/map.json")
        .then(response => response.json());
}

map.json:

[{"mapScale": 10}]

tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": true
    }
}

Upvotes: 0

Views: 334

Answers (1)

P.S.
P.S.

Reputation: 16384

That's because you specified an object type, which doesn't give much info about the data structure. If you aren't going to use specific typing, you can still use object or any types, but if you are, you should use types/interfaces for that, and specify returning values as well, something like this:

interface IItem {
  mapScale: number;
}

class Foobar {
  constructor(data: IItem[]) {
    console.log(data[0].mapScale);
  }
}

getMapObject()
  .then(function(data) {
    console.log(data);
    new Foobar(data);
  });

function getMapObject(): Promise<IItem[]> {
  return fetch('/map.json')
    .then(response => response.json());
}

You can also take a look at this post, to learn more about the object and any types: 'any' vs 'Object'.

Upvotes: 1

Related Questions