问题描述
当使用具有angular的ui状态的TypeScript时,我可以使用UI-Router明确类型的库提供type assertion。
When using TypeScript with angular's ui state, I can provide "type assertion" with the UI-Router definitely typed library.
使用这个,我可以注入 $ state
并且代码类似于以下
Using this, I can inject $state
and have code similar to the following
function myCtrl($state: ng.ui.IStateService){
// Some code
}
这为 $ state
的方法提供了正确的自动完成/错误报告。
This gives me correct autocompletion/error reporting for $state
's methods.
到目前为止,这一切都很好。
So far, this is all fine.
当我尝试访问 params
的属性时,如下所示
When I try to access a property of params
like the following
function myCtrl($state: ng.ui.IStateService){
// Trying to access a property of $state.params
var example = $state.params.example;
}
我收到错误消息:
因为非常正确,TypeScript不知道这个属性。
because quite rightly, TypeScript doesn't know about this property.
定义我自己的扩展 ng.ui.IStateService
interface IMyState extends ng.ui.IStateService{
params: {
example: string;
};
}
然后将类型设置为 my 界面
function myCtrl($state: IMyState){
var example = $state.params.example;
}
这消除了错误。
$ state
使用的正确类型是什么?
What is the correct type to use for $state
?
我应该定义我的像我的例子中那样拥有自己的界面?
Should I be defining my own interface like in my example?
推荐答案
使用Typescript,我们可以轻松扩展合约,随附 UI-Router
.d.ts 。
With Typescript, we really can easily extend a contract, coming with UI-Router
.d.ts.
所以这是原始定义(UI-路由器d.ts.文件):
// a state object
interface IStateService {
...
params: IStateParamsService;
...
// params
interface IStateParamsService {
[key: string]: any;
}
我们可以将这些行引入我们的自定义.d.ts
And we can just introduce into our custom .d.ts these lines
declare module angular.ui
{
export interface IStateParamsService { example?: string; }
}
这将使我们能够消费 $ state
及其params示例:
And that will now give us ability to consume $state
and its params with example:
MyMethod($state: ng.ui.IStateService)
{
let x = this.$state.params.example;
...
这篇关于具有params类型的类型的角度ui-state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!