自己的 Typescript 参考接口 属性
Typescript reference interface own property
我想使用接口的属性类型作为泛型,但我不确定是否支持我想做的事情。我会用代码来解释它:
通常我们可以这样做:
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
。我更愿意从分配给 属性 section
的值中去除 S
,像这样:
interface SezViewSettings = {
section: S extends Sections;
where: Array<keyof SectionEles[S]>;
}
这能做到吗?
没有泛型,接口无法表示此约束。
在这种情况下,您可能的 S
类型是 可枚举的 ,因此您可以为所有可能的 S
值并将其用作您的类型。这可能足以满足您的需求。
这是一种方法,方法是 mapped type whose properties are immediately looked up:
type SezViewSettingUnion = { [S in Section]: SezViewSettings<S> }[Section]
/* type SezViewSettingUnion = SezViewSettings<Section.users> |
SezViewSettings<Section.projects>
*/
同样,你可以使用distributive conditional types:
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>
。
好的,希望对您有所帮助;祝你好运!
Link to code
我想使用接口的属性类型作为泛型,但我不确定是否支持我想做的事情。我会用代码来解释它:
通常我们可以这样做:
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
。我更愿意从分配给 属性 section
的值中去除 S
,像这样:
interface SezViewSettings = {
section: S extends Sections;
where: Array<keyof SectionEles[S]>;
}
这能做到吗?
没有泛型,接口无法表示此约束。
在这种情况下,您可能的 S
类型是 可枚举的 ,因此您可以为所有可能的 S
值并将其用作您的类型。这可能足以满足您的需求。
这是一种方法,方法是 mapped type whose properties are immediately looked up:
type SezViewSettingUnion = { [S in Section]: SezViewSettings<S> }[Section]
/* type SezViewSettingUnion = SezViewSettings<Section.users> |
SezViewSettings<Section.projects>
*/
同样,你可以使用distributive conditional types:
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>
。
好的,希望对您有所帮助;祝你好运!
Link to code