I have a straightforward case in TypeScript, where I have an interface with a generic type T that extends an enum E. Based on the type a config type is assigned.
enum E { "A", "B" }
type ConfigsBase = { [K in E]: object }
interface Configs extends ConfigsBase {
[E.A]: { a: string };
[E.B]: { b: number };
}
interface MyInterface<T extends E> {
type: T;
config: Configs[T];
}
The question is how I can use this interface in a manner that the generic type is implicitly inferred from the object. So that I get useful type errors when the config is wrong.
const a: ??? = {
type: E.A,
config: { a: 1 },
}
// => I want this to give a typescript error because 1 is not a string
What do I need to insert for ??? so that typescript gives an error that the config is wrong. It should be something like const a: MyInterface<look for yourself what T is>.
I found a relatively tedious solution by using an identity function which infers the type automatically:
const inferType = <T extends E>(obj: MyInterface<T>): MyInterface<T> => obj
const a = inferType({
type: E.A,
config: { a: 1 },
})
// => TypeScript error: Type 'number' is not assignable to type 'string'
Is this possible to do this more elegantly with a type annotation without using a function?