Reputation: 13
When creating an interface for an options object, I'm trying to allow the user to specify a function with an explicit return type and a generic argument type. This is possible if you haven't defined a type for the function beforehand, but I can't figure out how to do it for a function type you've already defined.
For instance, this works just fine:
interface Options {
// Other options...
converterFunction: <T>(rawData: T) => [];
}
But this, which seems like a reasonable syntax, does not.
type ConverterFunction<T> = (rawData: T) => [];
interface Options {
// Other options...
converterFunction: <T>ConverterFunction<T>; // TypeScript is unhappy
}
Making the interface generic doesn't solve my problem, and I'd like to use my pre-defined types instead of re-defining them arbitrarily.
Upvotes: 1
Views: 4461
Reputation: 187252
A type that uses another generic type must either passes a concrete type, or be generic itself.
And <T>Type<T>
is not a valid syntax.
type ConverterFunction<T> = (rawData: T) => [];
interface Options<T> {
converterFunction: ConverterFunction<T>; // TypeScript is happy
}
const options: Options<string> = {
converterFunction(aString) {
return []
}
}
If the type is not named, you can define a function with a generic parameter, but if it is named, it seems this is not possible. I’m asking if this is indeed the case
It all depends on what level you want the generic passed in.
If you know it at the time you use the type, then it goes on the type.
type ConverterFunction<T> = (rawData: T) => T[];
const fn: ConverterFunction<string> = a => [a]
fn('a') // ['a']
Or if you want the generic type inferred by the function itself, then put it on the function.
type ConverterFunction = <T>(rawData: T) => T[];
const fn: ConverterFunction = (a: string) => [a]
fn('a') // ['a']
After reading your comments, it sounds like you want this second one.
Upvotes: 1