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

1
  • That's an object literal not a es6 Map? Commented Apr 6, 2020 at 10:43

2 Answers 2

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;
} = {};
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.