I am looking to restrict the calling party from inputting arbitrary strings as parameters to a method:
// A class that provides string values (urls)
class BackendUrls {
static USERS_ID = (id: string) => `/users/${id}`;
static CONSTANTS = () => '/constants';
}
// Base class containing the method in question (GET)
class BackendService {
protected GET<T>(url: string): Observable<T> {
// ...
}
}
// Calling party (subclass)
class UserService extends BackendService {
loadUser(id: string): Observable<User> {
return this.GET<User>(BackendUrls.USERS_ID(id));
// return this.GET<User>(`/users/${id}`); // <-- this also works
}
}
My goal is to constrain the parameter used in the BackendService->GET method.
How can I prevent UserService.loadUser(..) from using an arbitrary string and enforce usage of one of BackendUrls static members instead?
What I have attempted so far:
type BackendUrl = string;
class BackendUrls {
static USERS_ID = (id: string): BackendUrl => `/users/${id}`;
static CONSTANTS = () : BackendUrl => '/constants';
}
class BackendService {
protected GET<T>(url: BackendUrl): Observable<T> { // <-- ??
// ...
}
}
However, this approach still does not prevent the caller from providing a simple string:
return this.GET<User>(`/users/${id}`);
Edit: Note that the calling party should be mandated to use the functions provided by the BackendUrls class' static members.