I have a unique abstract class named 'AbstractDetailsService' defined as follows:
import { Injectable } from '@angular/core';
export class DetailEntities<T> {
id: number;
role: string;
data: T[];
}
export class User {
name: string;
age: number;
}
export class Customer {
customerName: string;
customerAge: number;
}
@Injectable()
export abstract class AbstractDetailsService<T> {
abstract get(entity: string): DetailEntities<T>;
}
Next, there is a class called 'PersonDetailsService' which implements the above class and can return either a User or a Customer based on the entity passed.
import { Injectable } from '@angular/core';
import { AbstractDetailsService, Customer, DetailEntities, User } from './abstract-detail.service';
@Injectable()
export class PersonDetailsService implements AbstractDetailsService<DetailEntities<any>> {
get(entity: string): DetailEntities<any> {
if (entity === 'user') {
const users: User[] = [{name: 'abc', age: 21}]
const userDetails: DetailEntities<User> = {id: 1, role: 'Developer', data: users};
return userDetails;
}
const customers: Customer[] = [{customerName: 'abc', customerAge: 21}]
const customerDetails: DetailEntities<Customer> = {id: 1, role: 'Developer', data: customers};
return customerDetails;
}
}
Presented below is my component code where I inject PersonDetailsService into the providers array:
import { Component, OnInit, VERSION } from "@angular/core";
import {
AbstractDetailsService,
DetailEntities,
User
} from "./abstract-detail.service";
import { PersonDetailsService } from "./person-detail.service";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
providers: [
{
provide: AbstractDetailsService,
useClass: PersonDetailsService
}
]
})
export class AppComponent implements OnInit {
name = "Angular " + VERSION.major;
details: DetailEntities<User>;
constructor(private readonly detailService: AbstractDetailsService<any>) {}
ngOnInit(): void {
const entity = "user";
this.details = this.detailService.get(entity);
}
}
I am seeking guidance on how to replace the generic type any
with either User
or Customer
. How can I customize the 'get' function to dynamically determine its return type? Additionally, I want to restrict the generic type to only accept User and Customer types.
For further exploration, visit this Stackblitz URL - https://stackblitz.com/edit/angular-typescript-dynamic-return-type?file=src%2Fapp%2Fperson-detail.service.ts
Your assistance on this matter would be greatly appreciated :-)