Is there a way to avoid to duplicate the <number>
and <string>
fn1
and fn2
signatures when calling the generic function?
interface Result<T> {
data: T
}
type ActionResponse<T> = Result<T>;
function fn1(): ActionResponse<number> {
return {
data: 1,
};
}
function fn2(): ActionResponse<string> {
return {
data: '1',
};
}
function generic<T>(fn: () => ActionResponse<T>): T {
const response = fn();
return response.data;
}
const res1 = generic<number>(fn1);
const res2 = generic<string>(fn2);
Is there a way to avoid to duplicate the <number>
and <string>
fn1
and fn2
signatures when calling the generic function?
interface Result<T> {
data: T
}
type ActionResponse<T> = Result<T>;
function fn1(): ActionResponse<number> {
return {
data: 1,
};
}
function fn2(): ActionResponse<string> {
return {
data: '1',
};
}
function generic<T>(fn: () => ActionResponse<T>): T {
const response = fn();
return response.data;
}
const res1 = generic<number>(fn1);
const res2 = generic<string>(fn2);
Share
Improve this question
asked Feb 1 at 22:04
njordnjord
1,28812 silver badges25 bronze badges
1 Answer
Reset to default 2You can simply omit the type parameter and allow it to be inferred:
const res1 = generic(fn1);
const res2 = generic(fn2);
See a full example at https://tsplay.dev/WYpAdm
Type inference is explained in the documentation on Generics:
Once we’ve written the generic identity function, we can call it in one of two ways. The first way is to pass all of the arguments, including the type argument, to the function:
let output = identity<string>("myString");
Here we explicitly set
Type
to bestring
as one of the arguments to the function call, denoted using the<>
around the arguments rather than()
.The second way is also perhaps the most common. Here we use type argument inference — that is, we want the compiler to set the value of
Type
for us automatically based on the type of the argument we pass in:let output = identity("myString");
Notice that we didn’t have to explicitly pass the type in the angle brackets (
<>
); the compiler just looked at the value"myString"
, and setType
to its type. While type argument inference can be a helpful tool to keep code shorter and more readable, you may need to explicitly pass in the type arguments as we did in the previous example when the compiler fails to infer the type, as may happen in more complex examples.