Why typeof body is resolve as Intersection Type SignRequest & {}.
export interface HttpResponse<T> {
statusCode: number;
body: T | Error;
}
export interface HttpRequest<T> {
body?: T;
}
export interface Controller {
handle<T>(httpRequest: HttpRequest<T>): HttpResponse<T>;
}
export class SignUpController implements Controller {
handle<SignRequest>(httpRequest: HttpRequest<SignRequest>): HttpResponse<SignRequest> {
if (httpRequest.body === null || httpRequest.body === undefined) {
throw new Error("Bad Request")
}
// **issue here**
const body = httpRequest.body; // body: SignRequest & {}
if (body !== null && body !== undefined){
console.log(body.name) // Error: Any: Property 'name' does not exist on type 'SignRequest & {}'
}
throw new Error("Not implemented exception");
}
}
export interface SignRequest {
name: string;
email: string;
password: string;
passwordConfirmation: string;
}
Any tips in how to access body.name in a more idiomatic way?
You don't want
handleitself to be generic, but the interfaceControlleritself:Then when you implement this interface, you would pass in the desired type:
Now the signature of
handlelooks like:and also
bodyis now of typeSignRequest:Playground