Prasad Shinde
Prasad Shinde

Reputation: 662

TypeScript map with keys having multiple types

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

Upvotes: 1

Views: 5791

Answers (2)

Yogi
Yogi

Reputation: 1722

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

Upvotes: 0

Prasad Shinde
Prasad Shinde

Reputation: 662

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;
} = {};

Upvotes: 3

Related Questions