1

How to declare a map in typescript where the key could be a string | number and the value could be for example a number.

I'm trying the following and get an error

let aMap : { [key: string | number]: number } = {}

I get the following error in VS Code

[ts] An index signature parameter type must be 'string' or 'number'.

Note: I do not want to use the keyword "Map" in typescript. As just declaring:

let aMap : { [key: string]: number } = {} works fine, I'm just having issues creating map with multiple key types

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Prasad Shinde
  • 652
  • 2
  • 8
  • 21

2 Answers2

3

Ahh, I figured out what was causing it finally. It's weird that I was not able to find this on the web. You can use the following syntax:

const testmap: {
  [key: number]: number;
  [key: string]: number;
} = {};
Prasad Shinde
  • 652
  • 2
  • 8
  • 21
0

From Typescript,

JavaScript object keys are always coerced to a string, so obj[0] is always the same as obj["0"].

Maybe the error is because number can also work with string.

I've found a situation that two custom types properties can be joined and result object contains anyone of the property. For that we can use Union or Intersection Types feature.

interface Colorful {
  color: string;
}
interface Circle {
  radius: number;
}
 
type ColorfulCircle = Colorful | Circle;

In the above code, ColorfulCircle can have both the properties of Colourful and Circle Source: TS - keyof, TS - Intersection, StackOverflow - Union vs Intersection

Yogi
  • 1,527
  • 15
  • 21