In TypeScript, I have created a QueryFactory
class with two generic type parameters: TQuery
and TResponse
. My goal is to ensure type safety so that if the TResponse
type does not match the expected response type of the TQuery
type, the compiler will throw an error.
Below is a snippet of my code:
// Object examples
class Person {
name: string;
age: number;
gender: string;
}
class Book {
name: string;
author: string;
}
// Classes
interface IBaseRequest {}
class RequestBase<T> implements IRequest<T>, IBaseRequest { }
interface IRequest<TResponse> extends IBaseRequest { }
class GetPersonByIdQuery extends RequestBase<Person> implements IRequest<Person>, IBaseRequest { }
class QueryFactory<TQuery, TResponse> { }
// Implementation
new QueryFactory<GetPersonByIdQuery, Person>(); // This is allowed as expected.
new QueryFactory<GetPersonByIdQuery, Book>(); // This should trigger a compilation error
new QueryFactory<GetPersonByIdQuery, string>(); // This should also result in a compilation error
I am looking for a way to enforce that the TResponse
type provided to QueryFactory
matches the expected response type of the TQuery
type. Specifically, the GetPersonByIdQuery
class should only permit Person as the response type.
Is there a method to implement this type safety check in TypeScript? How can I modify the QueryFactory
class to achieve this?