Home > database >  Passing type as constructor variable in TypeScript
Passing type as constructor variable in TypeScript

Time:12-17

I'm trying to create data service in Angular which will be universal to all CRUD HTTP requests. However, I want public functions to return typed Observable<T>. So I figured I'd pass a type into my service's constructor, store in in local variable and then each client object to instantiate this service class would supply 'type' it expects from service's return functions so that my post, put, patch, delete and get would return already typed Observable. Something like this:

    export class DataService {
constructor(private http: HttpClient, private dataType: Type )
}

getAll(): Observable<dataType[]> {
return http.get<dataType[]>(...);
}

post(dataIn: dataType): Observable<dataType> {
    return http.post<dataType>(...);
}
}

Can it be done?

CodePudding user response:

What you want is to have a generic type for your service class. TypeScript is compiled to JavaScript and will lose all the types in this process. The Following example shows how to use generic types for classes:

export class MyClassService<T = DefaultType> {

  constructor(private http: HttpClient) {}

  getSomeData(): Observable<T> {
    return this.http.get<T>(...)
  }
}

CodePudding user response:

Can it be done?

Kind of. You can achieve the result that you want, but not through the method that you are describing.

So I figured I'd pass a type into my service's constructor, store in in local variable

Types cannot be stored as variables because TypeScript types do not exist at runtime.

each client object to instantiate this service class would supply 'type' it expects from service's return functions

What you can do is turn DataService into a generic class. That means that each instance of DataService will have a different type T for its data.

You supply the type by setting the generic when you call the constructor:

const userService = new DataService<User>(client);
const commentService = new DataService<Comment>(client);

That generic class would look like this:

export class DataService<T> {
    constructor(private http: HttpClient) {
    }

    getAll(): Observable<T[]> {
        return this.http.get<T[]>(...);
    }

    post(dataIn: T): Observable<T> {
        return this.http.post<T>(...);
    }
}
  • Related