The title may be a bit unclear, but I'm struggling to find a better way to explain it.
I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for illustrating the situation
class Parent {}
class Child1 extends Parent {}
class Child2 extends Parent {}
Now, I need to create a function that will work with these classes
const doSomething = <T extends Parent>(someClass: T, options: SomeOptions<T>) => {}
doSomeThing(new Child1(), {foo: 'bar'});
doSomeThing(new Child2(), {id: 1});
Depending on the class provided, different sets of options are required. I want to define interfaces for these options to enable autocompletion. Ideally, it would look like this
interface SomeOptions {
Child1: {foo: string},
Child2: {id: number},
}
However, using classes as an index type is not possible. So, I'm thinking of structuring it like this instead
type SomeOptions = [
{class: Child1, options: {foo: string}},
{class: Child2, options: {id: number}},
]
Given this setup, how can I retrieve the correct options based on a class?
const doSomething = <T extends Parent>(someClass: T, options: FindMeTheCorrectOption<T>) => {}
My objective is as follows
doSomeThing(new Child1(), {foo: 'bar'}); // okay
doSomeThing(new Child2(), {id: 1}); // okay
doSomeThing(new Child2(), {foo: 1}); // TypeScript error, foo must be a string