Since T.J. Crowder's answer is correct, I'll just add some comments in case it helps understand better what is going on.
You have to remember that TypeScript adds static typing to JavaScript. That means that every entity defined in the language has a definite type, whether defined by you or inferred implicitly by TypeScript, and TypeScript will enforce observance of that type.
In your case, TypeScript implicitly infers that your IconSizeMap object is of a definite type. It's not a generic JavaScript object which can have any string key, but an object with some definite keys: extra-small, small, etc. TypeScript infers that from your definition of the object.
Once TypeScript has inferred a type for an entity, it will enforce it for every use you make of that entity. That means that if you try something like IconSizeMap['huge'] it will complain, since 'huge' was not registerd as a valid key in the type inferred by TypeScript.
This is quite easy to understand since 'huge' is explictly not contained in the object. But it has trickier consequences, like the problem you mentioned. If you are using variable size of type string to access the object properties, TypeScript will also complain because it can be possible that the value of size be a string not registered as one of the object keys. That's the reason for T.J.'s solutions:
- You either explicitly define the object's type as allowing any string key.
- You restrict the type of your string variables that will refer to object keys, so that they cannot be any string but just one of the strings contained in your object.
I suppose the second solution is what you need, since your object seems to be a fixed map, that doesn't allow further string keys. You can let TypeScript infer that implicitly, as in T.J's solution that uses a switch with only the expected string literals.
However, in situations like this I sometimes explicitly define union types containing those string literals. For example:
type IconSize = 'extra-small' | 'small' | 'medium' | 'large ' | 'extra-large';
I can then define variables explicitly with that type, and TypeScript will help me avoid assigning different string values to that variable:
let size: IconSize;
This means that TypeScript will rule out any attempt at setting a different string value to size. Since size will have one of the expected values, the next time you try IconSizeMap[size] TypeScript will not complain.