42
loading...
This website collects cookies to deliver better user experience
options
property on your object:class Fetcher {
constructor(public url = '/api', options?: RequestInit) {
this.#options = options;
}
#options?: RequestInit;
get options(): RequestInit {
return this.#options;
}
set options(val: RequestInit) {
this.#options = val;
this.fetch();
}
fetch() {
return fetch(this.url, this.options);
}
}
options
property with an accessor pair, we can run our side effects (in this case, calling fetch
) in the setter.Poster
class that only makes POST requests. It makes sense to extend Fetcher so that we don't duplicate our work. We want to narrow the type of options, however, to only allow options where the method
is POST
:type PostInit = RequestInit & { method: 'POST' };
class Poster extends Fetcher {
declare options: PostInit;
}
declare
keyword is "This class is exactly the same as it's parent, except that TypeScript should limit the options property to only accept PostInit objects". This should work, but...'options' is defined as an accessor in class 'Fetcher', but is overridden here in 'Poster' as an instance property.
declare
keyword, we don't have the problem of our class field overriding the accessors, particularly if we don't have useDefineForClassFields
turned on (which is probably a good choice anyways).declare
keyword.class Fetcher {
/** @internal */
static private o(proto: Fetcher, _: string) {
Object.defineProperty(proto, 'options', {
get() {
return this.#options;
},
set(val) {
this.#options = val;
this.fetch();
},
});
}
#options?: RequestInit;
@Fetcher.o options: RequestInit;
constructor(public url = '/api', options?: RequestInit) {
this.#options = options;
}
fetch() {
return fetch(this.url, this.options);
}
}
declare
our narrow type on the subclass.Poster
should implement it's own setter to only allow POST
at run time!