I have this function
function getCollection<T>(collectionType: T): Collection<T> {
return new Collection<T>()
}
and in Collection
class I have this
export class Collection<T> {
public add (item: T) {
// .. logic
}
}
I have a user interface defined like this
export interface IStudent {
}
and when I attempt to do
getCollection(IStudent).add({});
There is an error
TS2693: 'IStudent' only refers to a type, but is being used as a value here.
How do I make it accept generic type and returned strictly typed Collection?
CodePudding user response:
A generic type is a type parameter, not a function parameter. You define
function getCollection<T>(): Collection<T> {
return new Collection<T>()
}
(notice collectionType
was an unused parameter anyway) and then call it as
getCollection<IStudent>().add({});