In my example, I have created an Angular Service with multiple Generic Types that can be overridden through the methods. The issue I am encountering revolves around =
versus extends
and how it affects typing in the arguments. Strangely, using =
works perfectly for the return types but requires extends
for argument types.
class Service<
RequestBody,
ResponseBody,
CreateRequestBody = RequestBody,
CreateResponseBody = ResponseBody,
>
{
public createOne<
$CreateRequestBody extends CreateRequestBody,
$CreateResponseBody = CreateResponseBody
>(body : $CreateRequestBody) : $CreateResponseBody
{
return null;
}
public createTwo<
$CreateRequestBody = CreateRequestBody,
$CreateResponseBody = CreateResponseBody
>(body : $CreateRequestBody) : $CreateResponseBody
{
return null;
}
}
The examples below demonstrate the issue; I intend to use the createTwo()
method once I resolve the problem. Currently, it does not validate the type for body.
const service: Service<{ foo: string }, void> = new Service<{ foo: string }, void>();
// working
service.createOne({
foo: 'test'
});
// not compatible as the types do not match
service.createOne<void, void>({
bar: 'test'
});
// issue with body typing - not working as expected
service.createTwo({
bar: 'test'
});
// local override works correctly
service.createTwo<{ bar: 'test' }, void>({
bar: 'test'
});
You can also check out the behavior of the TypeScript compiler using this TypeScript Playground.