首页 > 解决方案 > 如何在 Typescript 中描述具有通用值的索引类型?

问题描述

有什么方法可以描述这个接口typescript

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

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

Collections对象包含List扩展Entity类的不同类对象。所以下面的代码不能解决我的问题:

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

上面的接口只为一个类A服务,我希望它服务于从类扩展的多个Entity类。

谢谢!

标签: javascripttypescript

解决方案


如果我抓住了这个想法,这可能是解决方案吗?

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'];

如果你不想关闭类型,你可以这样做:

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

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


推荐阅读