Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript引用接口自身属性_Typescript_Types_Typescript Generics - Fatal编程技术网

Typescript引用接口自身属性

Typescript引用接口自身属性,typescript,types,typescript-generics,Typescript,Types,Typescript Generics,我想使用接口属性的类型作为泛型,但我不确定我想做的是否受支持。我将用代码进行解释: 通常我们可以这样做: enum Sections { users = 'users', projects = 'projects' } interface SectionEles { [Section.users] : {...}; [Section.projects]: {...}; } interface SezViewSettings<S extends Sections>

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

通常我们可以这样做:

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

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

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

这能做到吗

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

在这种情况下,您可能的
S
类型是可枚举的,因此您可以为所有可能的
S
值形成一个
SezViewSettings
,并将其用作您的类型。这可能足以满足您的需要

这里有一种方法,通过创建一个属性立即为的:

type SezViewSettingUnion={[S in Section]:SezViewSettings}[Section]
/*类型SezViewSettingUnion=SezViewSettings |
SezViewSettings
*/
同样,您可以使用:

type\u SezViewSettingUnion=
有吗?SezViewSettings:永远不会;
类型SezViewSettingUnion=\u SezViewSettingUnion;
/*类型SezViewSettingUnion=SezViewSettings |
SezViewSettings*/
这两种方法最终都会产生相同的类型,相当于
SezViewSettings | SezViewSettings


好吧,希望这会有帮助;祝你好运

你不能用界面来完成。相反,您可以使用联合类型,比如SezViewSettingUnion=S扩展any?SezViewSettings:永远不会然后只需使用
SezViewSettingUnion
。这对你有用吗?如果没有,请说明您的用例。此外,请考虑编辑该代码,以适合于插入IDE并演示您的问题和唯一的问题(因此没有语法错误或未声明类型)。这就成功了。有点冗长,但适用于甲烷,这可以工作,但不幸的是,我得到的错误
类型实例化太深,可能无限
,所以我最终静态键入所有案例,我无法重现该错误;如果你能提出一个建议,我也许能提供一些建议。否则,祝你好运!这是一个常见的错误,TS抛出然后类型推断依赖于太多的递归,这不是代码本身的错误。这真的很难重现,因为代码需要深入到遇到错误的地方,此时最好静态声明一些类型。
interface SezViewSettings = {
  section: S extends Sections;
  where: Array<keyof SectionEles[S]>;
}
type SezViewSettingUnion = { [S in Section]: SezViewSettings<S> }[Section]
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
     SezViewSettings<Section.projects>
*/
type _SezViewSettingUnion<S extends Section> =
    S extends any ? SezViewSettings<S> : never;
type SezViewSettingUnion = _SezViewSettingUnion<Section>;
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
SezViewSettings<Section.projects> */