I'm trying to map/match a class type to another type via a generics. An example will make that clearer:
class BaseClass {
//...
public someGenericClassStuff: 'someGenericClassStuff' = 'someGenericClassStuff';
}
class BaseProps {
//...
public someGenericStuff: 'someGenericStuff' = 'someGenericStuff';
}
class FooClass extends BaseClass {
//...
public someFooClassStuff: 'someFooClassStuff' = 'someFooClassStuff';
}
class FooProps extends BaseProps {
public someFooSpecificStuff: 'someFooSpecificStuff' = 'someFooSpecificStuff';
//...
}
class BarClass extends BaseClass{
//...
public someBarClassStuff: 'someBarClassStuff' = 'someBarClassStuff';
}
class BarProps extends BaseProps {
public someBarSpecificStuff: 'someBarSpecificStuff' = 'someBarSpecificStuff';
//...
}
type AllClass = BarClass | FooClass;
type AllProps = BarProps | FooProps;
type SpecificProps<T extends AllClass> = // Wondering what goes here
const test: SpecificProps<BarClass> = new BarProps(); // Works
const test2: SpecificProps<FooClass> = new FooProps(); // Works
const test3: SpecificProps<BarClass> = new FooProps(); // Fails
I tried a few options, here's what is getting me the closest:
type SpecificProps<T extends AllClass> =
T extends BarClass ? BarProps :
T extends FooClass ? FooProps :
never;
This solution works pretty decently in my example above, but when I start adding more and more classes and Unions between them it starts to fall apart and sometimes will return me wrong types. Also it's not the most convenient to write as I have a lot more than 2 classes and each time I add one I need to augment this type too.
My ideal solution would be to do something like
class BarClass extends BaseClass {
//...
public someBarClassStuff: 'someBarClassStuff' = 'someBarClassStuff';
type props = BarProps;
}
// And my type would become
type SpecificProps<T extends AllClass> = T['props'];
But I know this doesn't exist in typescript. I would have to create an actual variable instead of a type and it would take up memory for nothing other than the type matching.