Assume a library exposes function like this
export function getData<Data extends BaseData>(dataPath: string) {
// Do work
}
If I import this function, is there any way I can access and store type of it's generic (Data extends BaseData
) bit inside my own type MyType
value, to reference it latter on?
Current issue I am facing is that BaseData
from the library is not exported, thus I can't really use it (worst case I can replicate it, but I am wondering if there is more cleaner solution, something like ReturnType
util, but for this constraint / generic)
CodePudding user response:
Assuming that the generic is used somewhere where you can use infer
on it (i.e., in the parameter list or return type), you can get the type it extends.
If it is not used in one of those places, there is no way to get it.
E.g., there is no way to get the BaseData
from getData<Data extends BaseData>()
.
I'll assume there is a function getData
defined as follows:
declare function getData<Data extends BaseData>(data: Data): any;
You now have two options: you can create your own generic to extract the type, or you can use Parameters
.
// Using `Parameters` and the index of the parameter you need.
type FromParam1 = Parameters<typeof getData>[0]; // BaseData
// Using a custom generic.
type TypeOfParam<T> = T extends (param: infer Param) => void ? Param : never;
type FromParam2 = TypeOfParam<typeof getData>; // BaseData
The custom generic is useful if the type you want is wrapped in other types:
declare function getData<Data extends BaseData>(
data: Record<string, Data>
): any;
type TypeOfParam<T> = T extends (param: Record<string, infer Param>) => void
? Param
: never;
type FromParam = TypeOfParam<typeof getData>; // BaseData
If the type is in the return type, you can get it using the same principles.
CodePudding user response:
try to import BaseData
and use it in your type assuming the same constraints