Is it possible to set a variable based on a TypeScript Generic?
class Foo<T> {
constructor() {
// This doesn't actually work but it's essentially what I would like to do
const myKey = (T extends number ? 'myNumber' : null);
}
}
Here is a more complete example that will work in an external IDE. The objective here is to instantiate the Animal class with the appropriate generic (Dog | Cat) while also giving the constructor the ability to get a subset of the Object returned from getUpdate. In the below example, this is done with myKey. To reiterate on my original question, is there a way to perform all of this without having "Dog" appear 2 times when instantiating the class?
interface Dog {
bark: string;
}
interface Cat {
meow: string;
}
type AnimalType<T> =
T extends Dog ? Dog :
T extends Cat ? Cat : null;
const getUpdate = (): Record<string, Dog | Cat> => ({
dog: { bark: 'woof' },
cat: { meow: 'meow' },
});
class Animal<T> {
public state!: AnimalType<T>;
constructor(myKey: 'dog' | 'cat') {
this.state = getUpdate()[myKey] as AnimalType<T>;
}
}
// dogInstance is of type `Animal<Dog>` with a state of `{ bark: 'woof' }`
const dogInstance = new Animal<Dog>('dog');
class FooNumber { ... myKey = 'myNumber'andclass FooNull { ... myKey = null? Right now it doesn't look likeTserves much of a purpose; can you expand out to a minimal reproducible example if you want more targeted advice?new Foo('MyType')infersMyTypeforT, but without a true minimal reproducible example as described in How to Ask, I'm not going to guess about it. Looks like you've already accepted the answer below, which still requiresnew Foo<MyType>('MyType'), so I must be missing something about the use case. If you edit your question with an example that can be dropped into a standalone IDE and demonstrate the issue, I'll take a look. Otherwise, good luck!