简体   繁体   中英

typescript generics interface, method parameter and method return type

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?

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({});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM