繁体   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