打字稿参考界面自己的属性

我想将接口的属性类型用作泛型,但是我不确定是否支持我想做的事情。我将用代码进行解释:

通常我们可以这样做:

enum Sections {
  users = 'users',projects = 'projects'
}

interface SectionEles {
  [Section.users] : {...};
  [Section.projects]: {...};
}

interface SezViewSettings<S extends Sections> = {
  section: S;
  where: Array<keyof SectionEles[S]>;
}

这很好,但是我想避免将SezViewSettings设为generic。我希望从分配给属性S的值中减去section,像这样:

interface SezViewSettings = {
  section: S extends Sections;
  where: Array<keyof SectionEles[S]>;
}

可以做到吗?

ayaya1234 回答:打字稿参考界面自己的属性

没有泛型,接口无法表示此约束。

在这种情况下,您可能的S类型是可枚举的,因此对于所有可能的SezViewSettings<S>值,您可以形成S的{​​{3}}并将其用作您的类型。这可能足以满足您的需求。

这是一种方法,方法是制作一个union,其属性立即为mapped type

type SezViewSettingUnion = { [S in Section]: SezViewSettings<S> }[Section]
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
     SezViewSettings<Section.projects>
*/

类似地,您可以使用looked up

type _SezViewSettingUnion<S extends Section> =
    S extends any ? SezViewSettings<S> : never;
type SezViewSettingUnion = _SezViewSettingUnion<Section>;
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
SezViewSettings<Section.projects> */

这两个最终都产生相同的类型,等同于SezViewSettings<Section.users> | SezViewSettings<Section.projects>


好的,希望能有所帮助;祝你好运!
distributive conditional types

本文链接:https://www.f2er.com/3150093.html

大家都在问