I'm running into an issue where I have an interface that describes some dynamic data where the values of each property can be one of many types, but I can't assign a variable that is one of those types.
Here's my interface:
interface MyDict {
[key: string]: string | number;
}
Here's some data of that type:
const data: MyDict = {
hello: 'world',
test: 123,
};
However when I try to pull values from data and assign it to a variable typed string or number, it fails.
const example: string = data.hello;
/* ->
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'. ts(2322)
*/
data.hello is allowed to be either a string or a number, in this case it is a string, but when I try to assign it to variable example that can only be a string it unexpectedly fails. I'm under the impression that I can think of | as "or", but perhaps I'm wrong. Is there something I'm missing about union types? I'd really appreciate some pointers! :)
EDIT: I was able to get it to work by casting data.hello to a string, like so:
const example: string = data.hello as string;
Is this the right solution here, or is there a better practice for this use case?
string | number. Compilers aren't magic, they're just very clever at certain things, and this level of flow analysis is not one of them.