打字稿中带有params类型的Angular ui-state [英] Angular ui-state with params type in typescript
问题描述
当使用带有 angular 的 ui 状态的 TypeScript 时,我可以提供类型断言";使用 UI-Router 绝对类型库.
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;
}
我收到一条错误消息:
IStateParamsService 上不存在属性示例"
Property 'example' does not exist on IStateParamsService
因为完全正确,TypeScript 不知道这个属性.
because quite rightly, TypeScript doesn't know about this property.
定义我自己的接口来扩展 ng.ui.IStateService
interface IMyState extends ng.ui.IStateService{
params: {
example: string;
};
}
然后设置类型为我的界面
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-Router 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
及其参数,例如:
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类型的Angular ui-state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!