Reputation: 55
add edge method throw this error. I don't know what is never in this case!
TS2345: Argument of type 'string | number' is not assignable to parameter of type 'never'.
export class Graph {
adjacencyList: { [key in string | number]: string[] | number[] } = {};
addVertex(vertex: string | number): void {
this.adjacencyList[vertex] = [];
}
addEdge(vertex1: string | number, vertex2: string | number): void {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
}
Thanks
Upvotes: 0
Views: 1296
Reputation: 70564
The problem is that your type
{ [key in string | number]: string[] | number[] }
says that each key maps to either a string[]
or a number[]
, but doesn't say which it is. Therefore, when you try to push a key, TypeScript can not know that the key is of a type suitable for the array. For instance, for all TypeScript knows, the key could be a string
, but the array a number[]
...
(granted, the error message could be clearer ...)
You can resolve this in different ways. If each graph either deals with strings or numbers, but not usually both, you could use generics:
export class Graph<V extends string | number> {
adjacencyList: { [key in V]?: V[] } = {};
addVertex(vertex: V): void {
this.adjacencyList[vertex] = [];
}
addEdge(vertex1: V, vertex2: V): void {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
}
(the compiler still yells at you because the edge may have been added before the vertex is, resulting in a missing array. You may want to handle that more gracefully)
Alternatively, if your Graph typically contains any mixture of numbers and strings, you could do:
export class Graph {
adjacencyList: { [key in number | string]: (number | string)[] } = {};
addVertex(vertex: number | string): void {
this.adjacencyList[vertex] = [];
}
addEdge(vertex1: number | string, vertex2: number | string): void {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
}
The relevant change is that adjacencyList
of a vertex is of type (number | string)[]
, i.e. an array that can contain a mixture of strings and numbers.
Upvotes: 1