简体   繁体   English

如何用 Typescript 中的泛型值描述索引类型?

[英]How to describe an index type with generic values in Typescript?

Is there any way to describe this interface in typescript :有什么方法可以在typescript中描述这个接口:

abstract class Entity { /*...*/ }
interface List<A extends Entity> { /*...*/ }

// I want the below interface
interface Collections {
  [name: string]: List<A extends Entity>;
}

The Collections object contains different List objects of classes that extend the Entity class. Collections object 包含扩展Entity class 的类的不同List对象。 So the following code doesn't solve my problem:所以下面的代码不能解决我的问题:

interface Collections<A extends Entity> {
  [name: string]: List<A>;
}

The above interface serves only for one single class A , I want it to serve multiple classes extend from Entity class.上面的接口只为一个单一的 class A服务,我希望它服务于从Entity class 扩展的多个类。

Thank you!谢谢!

If I caught the idea, this might be the solution?如果我抓住了这个想法,这可能是解决方案吗?

abstract class Entity { /*...*/ }
class Book extends Entity { title = 'default'; }
class Spoon extends Entity { price = 5; }

interface List<A> { /*...*/ }
interface EntityList extends List<Entity>{}

interface Collections {
  [name: string]: EntityList
}

const t: Collections = {
  'test': [new Book(), new Spoon()]
}

const x = t['test'];

If you don't wont to close type you might do this:如果你不想关闭类型,你可以这样做:

interface Collections<T> {
  [name: string]: List<T>
}

const t: Collections<Entity> = {
  'test': [new Book(), new Spoon()]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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