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
Angular 有没有办法让intellisense知道具有动态索引的接口的实例成员?_Angular_Typescript_Visual Studio Code - Fatal编程技术网

Angular 有没有办法让intellisense知道具有动态索引的接口的实例成员?

Angular 有没有办法让intellisense知道具有动态索引的接口的实例成员?,angular,typescript,visual-studio-code,Angular,Typescript,Visual Studio Code,我正在处理一个角度项目,我正在使用一个接口来定义一个模块的配置。该界面旨在将名称映射到对象,非常简单: export interface NamedRoutes { [routeName: string]: NamedRoute; } 当我创建该接口的实例时,当我使用它时,intellisense无法解析实例的成员。例如: const routes: NamedRoutes { someRoute: {...} }; const someRoute = routes. // no i

我正在处理一个角度项目,我正在使用一个接口来定义一个模块的配置。该界面旨在将名称映射到对象,非常简单:

export interface NamedRoutes {
  [routeName: string]: NamedRoute;
}
当我创建该接口的实例时,当我使用它时,intellisense无法解析实例的成员。例如:

const routes: NamedRoutes {
  someRoute: {...}
};

const someRoute = routes. // no intellisense support here
据我所知,问题是,当编译器试图回溯成员时,它看到索引是字符串,因此可以允许任何内容,因此它无法建议实际存在的成员

当我省略常量的输入时,intellisense能够提示正确的成员。据我所知,这是因为索引名随后被解释为符号,而不是字符串。缺点是,当我的API用户将对象传递给我的配置方法时,他们只会获得编译器对错误的支持,在我们的项目中,配置方法可能位于与对象创建完全不同的位置。在我看来,这对于api来说是一个非常糟糕的UX

我尝试使用不同的高级类型,如
Record
(用于索引类型)

我希望,我明确表示,我的问题是什么,我正在努力实现什么。有没有一种方法可以做到这一点


注意:使用类型而不是接口也将是我们项目的一个选项。

您可以为用户提供一个帮助函数,用户可以使用该函数创建
namedrotes
实例,而不是让他们使用
namedrotes
注释。大概是这样的:

// I like examples that compile, so here's something random:
interface NamedRoute {
    whoKnows: string; 
}

export interface NamedRoutes {
    [routeName: string]: NamedRoute;
}

// helper function that just returns the input but makes sure it conforms to NamedRoutes    
const asNamedRoutes = <T extends NamedRoutes>(t: T) => t;

// correct use
const routes = asNamedRoutes({
    someRoute: { whoKnows: "blah" }
});

routes.someRoute // IntelliSense is here, yay!

// incorrect use so you still get early errors
const badRoutes = asNamedRoutes({
    badRoute: { nobodyKnows: "whoops " } // error!
    // type { nobodyKnows: string } is not assignable to NamedRoute
})
//我喜欢编译的示例,下面是一些随机的:
接口名称{
谁知道呢:弦;
}
导出接口名称{
[路由名称:字符串]:namedRoote;
}
//只返回输入但确保其符合NamedRoots的帮助函数
常数asnamedulotes=(t:t)=>t;
//正确使用
const routes=asNamedRoutes({
someRoute:{谁知道:“废话”}
});
routes.someRoute//IntelliSense在这里,耶!
//使用不正确,因此仍然会出现早期错误
const badRoutes=asnamedulotes({
错误路线:{nobodyKnows:“哇”}//错误!
//类型{nobodyKnows:string}不可分配给NamedLote
})
asnamedRootes()
函数本质上与强制人们在通常情况下提前将对象传递给方法相同,因此错误会提前出现。您可以做一些事情来减少对
namedootes
的注释(使
namedootes
具有私有成员的类具有这种效果),但这可能有些过分了


希望有帮助。祝你好运

谢谢你的意见!我希望避免使用helper函数,但至少,这会将编译器错误移到创建行。