簡體   English   中英

使用類型特定的接口的鍵定義類型約束

[英]Define type constraint with the keys of an interface whose type is specific

讓我澄清一下問題。 我有一個接口,其鍵是標簽名稱,每個鍵的類型是相應的自定義元素類。

// custom element class
class View extends HTMLElement { ... }
abstract class ScrollLayout extends View { ... }
class ListView extends ScrollLayout { ... }
class GridView extends ScrollLayout { ... }

// Tag to Class
interface Tag2Class {
    "p-view": View;
    "p-list-view": ListView;
    "p-grid-view": GridView;
}

現在,我想定義另一個接口,它有一個名為layout的鍵,其類型是Tag2Class類型的ScrollLayout的鍵

interface Attrs {
    layout?: ??? // I want the type to be "p-list-view" | "p-grid-view" | undefined
}

有沒有辦法實現這個? 我試過記錄<>

interface Attrs {
    layout?: keyof Record<keyof Tag2Class, ScrollLayout>;
}

但奇怪的是, layout類型還包含"p-view" 我不明白為什么結果會這樣,因為上面的 Record 類型會返回類型{ [P in keyof Tag2Class]: ScrollLayout } ,而這個 keyof 只會是"p-list-view" | "p-grid-view" "p-list-view" | "p-grid-view"

您可以使用此處KeyOfType來過濾特定類型的鍵:


type KeyOfType<T, U> = { [P in keyof T]: T[P] extends U ? P : never }[keyof T]

interface Attrs {
    layout?: KeyOfType<Tag2Class, ScrollLayout> //  "p-list-view" | "p-grid-view" | undefined
}

游樂場鏈接

暫無
暫無

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

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