Reputation: 3341
I need to try and get the generic type passed into a class in TypeScript.
See my example below, I initialize my class with type 'hello' | 'goodbye'
I then want to create a function with has the parameter of the type passed into the original class.
Is this possible?
class MyTestClass<T> {
doSomething = (myType: T, count: number) => {
// ...
}
}
const myTest = new MyTestClass<'hello' | 'goodbye'>()
const myNewMethod = (subType: typeof myTest) => {
// I want subType to be 'hello' | 'goodbye'
}
Upvotes: 1
Views: 64
Reputation: 7573
You can use conditional types wit the infer
keyword to extract the U
from MyTestClass<U>
type subType = typeof mytest extends MyTestClass<infer U> ? U : never;
Here, if myTest
is any kind of MyTestClass<X>
, then subType
will be the X
, otherwise it will be never
(which won't ever happen since your myTest
is explicitly a MyTestClass
.
Upvotes: 1