I’ve got some code that maps ‘to -> from’ types like this:
/**
* From types:
*/
type Kitten = {
kind: 'kitten';
};
type Puppy = {
kind: 'puppy';
};
/**
* To types:
*/
type Cat = {
kind: 'cat';
};
type Dog = {
kind: 'dog';
};
/**
* Existing generic "condtional type" that converts any "FROM" -> "TO" using nested ternaries (slow when big):
*/
type ConvertType<T> = T extends Kitten ? Cat : T extends Puppy ? Dog : never;
However in reality, there’s 100+ pair mappings, and therefore nested ternary conditions, which really slows TypeScript down.
Is there some better way to do this without using a slow “conditional type”?
I know it could also be done with a dummy function with overloads like this…
function convert_function(input: Kitten): Cat;
function convert_function(input: Puppy): Dog;
function convert_function(input: unknown) {
return input;
}
…but I’m wondering if it can just be done purely with the typing system alone, as I am already with ConvertType<T>
, but without the performance issues.