Why I can't call keys() on a Typescript Map?

549 Views Asked by At

In a Typescript program (3.9.6), I have a variable p that I believe to be a Map. From console.log(p) I get:

Map(2) { 'A' => 0, 'B' => 2}

However, it looks like I can't get the keys: console.log(p.keys()) cannot even compile:

 error TS2349: This expression is not callable.
 Type 'Number' has no call signatures.
 console.log(p.keys());

The variable p seems to come from here:

function f(q: IQ){
   ...
   let p=q.data;
   console.log(p);
   console.log(p.keys());
   ...

where IQ is defined as

export interface IQ {
   data: IData;
}
export interface IData {
     [key: string]: number
}

No idea what is wrong, I'm stuck

1

There are 1 best solutions below

4
On BEST ANSWER

p is of type IData, not Map (or at least that is how TypeScript sees it at compile time).

If it is really an IData at runtime, use Object.keys(p) to get the keys.

If it is really a Map, you can cast it like console.log((p as any as Map<string, number>).keys()). However, this means that the types are incorrect and it is better to fix the types instead of casting.