I am working with a mapped type in the following structure:
type Mapped = { [Key in string]: Key };
My understanding is that this setup should only allow types where the key matches the value. However, I have found that both of the cases below are permitted:
function handleMapped<const T extends Mapped>(t: T): T {
return t;
}
// the desired case
const mapped1 = handleMapped({
'foo': 'foo ',
});
// should not be allowed
const mapped2 = handleMapped({
'foo': 'bar',
});
Is there a way to enforce the intended constraint? Additionally, it's important to note that the ultimate goal is to enable recursive nesting of Mapped
objects within each other. Using generic type parameters for this purpose is challenging due to issues with recursive types. The final type structure will resemble this:
type Mapped = {
[Key in string]: {
fn: (key: Key) => void,
children: Mapped
}
};
Ensuring proper typing for the parameter of fn
is crucial.