Fix the builder so chained calls keep the subclass type.
JsonRequestBuilder adds a body method, but after .header(…) or .timeout(…) TypeScript only knows the value is a RequestBuilder, so .body(…) is an error. Change the types so a chain started on a JsonRequestBuilder stays one, without overriding header and timeout in the subclass.
class RequestBuilder { protected headers: Record<string, string> = {}; protected ms = 5000; header(name: string, value: string): RequestBuilder { this.headers[name] = value; return this; } timeout(ms: number): RequestBuilder { this.ms = ms; return this; } build() { return { headers: this.headers, timeout: this.ms }; }} class JsonRequestBuilder extends RequestBuilder { private data: unknown; body(data: unknown) { this.data = data; return this; } build() { return { ...super.build(), body: JSON.stringify(this.data) }; }} // new JsonRequestBuilder().header("Accept", "application/json").body({ id: 1 }).build();The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…