I'm going to be answering my own question here.
Whenever we are structuring an "object key type" we are constrained by the types that typescript defined which are string
, number
, symbol
and those are also the only types accepted as a javascript object key.
The compiler didn't like the generic type K
only without the extend
because it can literally be anything e.g null
and that's not a valid key value.
Therefore, if we want to constrain the type of the key to an acceptable type we pass in our object declaration. we have to first tell the generic type in this case K
which types it can be in this case string | number
.
interface SomeObj<K extends string | number , V> {
something: {
[key in K]: V;
}
};
const foo: SomeObj<string, number> = {
something: {hello: 1234}
}
const bar: SomeObj<number, number> = {
something: {123: 1234}
}