Consider the following code:
const testOne: Record<"foo"|"bar", string> = {
"foo": "xyz"
};
const testTwo: Record<string, string> = {
"foo": "xyz"
};
The first example causes an error that property "bar" is missing. The second example does not cause an error. This confuses me because I'm trying to understand whether Record is a type that implies an existing property for all possible values of its key type or not.
If Record is meant to be a type that does not demand all possible keys to actually exist in a value of that type, then the first example should not cause an error.
If Record is meant to be a type that demands all possible keys to actually exist in a value of that type, then the second example should cause an error too. In this case it would be impossible to construct a value of that type because the set of possible keys is infinite.
If there is a third alternative -- which there seems to be according to what really happens when I try to compile the example -- what is it? The main difference I can see between the two key types is that one has a finite set of values, the other has an infinite set of values. Is this used as the distinction?
Other than that, the only explanation I can find is that Record makes a distinction not only based on the set of values of its key type, but some other property of its key type too. If so, what property of the key type does make the difference? Or does Record do the type system equivalent of "bypass the interface, cast to the implementation type and do something you're not supposed to do"?
The implementation of Record is
type Record<K extends keyof any, T> = {
[P in K]: T;
};
I can spot two things here. The first is the bound on K to "keyof any", but to my knowledge this limits what types can be used for K, not what values are valid for the resulting type. Second, we have a normal index signature, so my guess would be that what I am confused about in Record is actually the behaviour of index signatures -- but I could not reproduce this behavior without Record easily due to other problems, so I don't want to jump to conclusions.