It is uncertain whether {id: 1}
represents a valid value of type T
. The constraint T extends Entity
indicates that T
can be any subtype of Entity
defined by the code calling the constructor of SearchServiceBase
. Therefore, within the context of the implementation of GetAll()
, the exact nature of T
remains unknown.
To illustrate this point, consider revising your code to a more concise minimum reproducible example which eliminates dependencies on Angular:
class Entity {
id: number = 0;
}
class SearchServiceBase<T extends Entity> {
public GetAll() {
const values: T[] = [
{ id: 1 } //<-- ERROR Cannot assign to type T
];
}
}
Now, let's examine how the following code scenario plays out:
class Hmm extends Entity {
readonly hmm = "hmmmmmm";
}
const hmmSearch = new SearchServiceBase<Hmm>();
hmmSearch.GetAll(); // 🤔
When you execute hmmSearch.GetAll()
, it equates to:
class HmmSearchServiceBase {
public GetAll() {
const values: Hmm[] = [
{ id: 1 } //<-- ERROR Property 'hmm' is missing
];
}
}
As evidenced, {id: 1}
does not align with the definition of Hmm
. Hence, the compiler rightfully flags an error in your original code snippet.
Unfortunately, resolving this issue poses a challenge for me as I lack sufficient familiarity with Angular and RxJS to grasp the purpose behind your operations. Assigning a concrete type value to a generic type variable often proves intricate due to the need to ensure compatibility across all potential instantiations of the generic type. If you aim to obtain a generic type T
, you may require its provision through a function parameter or class constructor argument.
In any case, I hope my insights prove beneficial. Best of luck!
Link to code