我有一个类似这样的泛型类,但我想用T传递附加值
@Injectable()
export class Repository<T,// value //> {
constructor(){
let _value = value;
}
}-用法-
@Injectable()
export class ProductService {
constructor(private repo: Repository<Product, //string or numeric value//>) {
}我想实现这样的东西,我如何在typescript中传递带有泛型参数的字符串或数值。
发布于 2018-01-04 18:02:30
泛型类型满足于类型参数,而不是文字值(尽管您可以用它做一些非常时髦的事情-但在您的情况下,您不需要这样做)。
您可以接受一个listType并将其限制为string或string文本类型,如下所示(它看起来像一个联合类型,但它的类型成员是String值)。
class Repository<T> {
private itemsRef: T[];
constructor(private db: AngularFireDatabase, listType: 'products' | 'customers') {
this.itemsRef = db.list(listType);
}
}它的脆弱之处在于,使用者可能会传递不兼容的T和listType -因此您可能希望创建一个RepositioryFactory来防止这种情况。
工厂变体
这是一个带有工厂方法的版本,它可以防止不兼容错误。
type ListType = 'products' | 'customers';
class Repository<T> {
private itemsRef: T[];
protected constructor(private db: AngularFireDatabase, listType: ListType) {
this.itemsRef = db.list(listType);
}
static getInstance(db: AngularFireDatabase, listType: 'products'): Repository<Product>;
static getInstance(db: AngularFireDatabase, listType: 'customers'): Repository<Customer>;
static getInstance(db: AngularFireDatabase, listType: ListType) {
switch (listType) {
case 'products':
return new Repository<Product>(db, listType);
case 'customers':
return new Repository<Customer>(db, listType);
default:
throw new Error(`No Respository<T> for ${listType}`);
}
}
}https://stackoverflow.com/questions/48085580
复制相似问题