Home > Mobile >  Element implicitly has an 'any' type because expression of type 'number' can
Element implicitly has an 'any' type because expression of type 'number' can

Time:06-01

I know there are multiple questions of this type, but I tried almost everything and I am still getting this error. I am working in a vue project. I have defined my data as follows:

data(){
    return{
      nodes: {},
      edges:{},
      nextNodeIndex: 0,
      nextEdgeIndex: 0,
      selectedNodes: [],
      selectedEdges: [],
      graph: ref<vNG.Instance>() 
    }
  }

Now inside a method I am writing a function to addNode

 addNode() {
      const nodeId = this.nextNodeIndex
      this.nodes[nodeId] = {
        name: String(nodeId),
        size: 16,
        color: "blue",
        label: true
      } 

the line this.nodes[nodeId] is giving the error Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.. Most of the solutions I found were telling to define the dict as const dict = {key:string} but since I am defining the nodes in data I can not use const.

Any suggestions are very much appreciated.

CodePudding user response:

You could explicitly type the return type of data:

data(): { nodes: ..., ... } {

}

But that would mean you would have to write a lot of types that TypeScript could've inferred.

I'd settle for an assertion instead:

nodes: {} as { [key: number]: { name: string; size: number; ... } },

And maybe even for edges:

edges: {} as { [key: number]: ... },

However, seeing that the keys are numbers, you might want to consider using an array instead of an object.

CodePudding user response:

A simple way to annotate both types and initial values without declaring anything twice is to use a barebones class for data:

class Data {
  // TODO: Fill in correct types instead of `unknown`
  nodes: Record<number, unknown | undefined> = {};
  edges: Record<number, unknown | undefined> = {};
  nextNodeIndex = 0;
  nextEdgeIndex = 0;
  selectedNodes: unknown[] = [];
  selectedEdges: unknown[] = [];
  graph = ref<vNG.Instance>() 
}

And then in your data method return an instance:

data() {
  return new Data();
}

This is slightly misleading as you don't want to actually use this class as a class outside of that nor add methods to it, but it is the least verbose way. It's handy so long as you don't misuse it.

  • Related