javascript - 如何在 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
类。
谢谢!
解决方案
如果我抓住了这个想法,这可能是解决方案吗?
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()]
}
推荐阅读
- asp.net-core-mvc - 添加到用户的角色确实在 IsInRole 中给出错误
- c# - 如何将用户文件选择链接到 StringSplit
- autocomplete - PhpStorm 将“null”自动完成为“null()”。我可以修改自动完成列表吗?
- javascript - 如何仅使用取决于我的选择选项参数的新 API 重绘 Highchart?
- android - Android如何获取Ibeacon X轴正负值?
- php - 如何从个性化下拉列表中获取值?
- javascript - Asyncronos onsubmit 处理程序
- postgresql - 超过 application_name 字符长度
- spring - 如何跨微服务部署代码更改?
- google-analytics - Google Analytics(分析)自定义维度未通过