Can a TypeScript index signature type be used to enforce that every index adheres to a generic interface? I want to define code like this:
interface HasState<T> {
state : T;
}
interface ModuleDefinition {
[moduleName : string] : <T>HasState<T>;
}
Let's consider a scenario:
I have a TypeScript mapped type for an object:
interface ModuleDefinition {
[moduleName : string] : HasState;
}
interface HasState {
state : any;
}
This setup ensures that each value in a ModuleDefinition object includes a property named state.
However, when trying to extract the state objects using the mapped type:
type UnwrappedModules<Mod extends ModuleDefinition> = {
[K in keyof Mod] : Mod[K]["state"];
}
and defining a function like this:
function unwrap<Mod extends ModuleDefinition>(mod: Mod) : UnwrappedModules<Mod> {
// ...
}
const result = unwrap({
apple: {
state: {
color: 'red'
}
}
}).apple
The variable result
is of type any instead of { color : string }
, which is unexpected. Is there a way to correctly infer the type in such cases in TypeScript?