簡體   English   中英

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

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

有什么方法可以在typescript中描述這個接口:

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

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

Collections object 包含擴展Entity class 的類的不同List對象。 所以下面的代碼不能解決我的問題:

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

上面的接口只為一個單一的 class A服務,我希望它服務於從Entity class 擴展的多個類。

謝謝!

如果我抓住了這個想法,這可能是解決方案嗎?

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()]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM