'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
Solution 1:[1]
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;
} = {};
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prasad Shinde |
| Solution 2 |
