Angular ui-state with params type in typescript

Angular ui-state with params type in typescript

我所知道的

在 angular 的 ui 状态下使用 TypeScript 时,我可以使用 UI-Router 确定类型库提供“类型断言”。

使用这个,我可以注入 $state 并得到类似于下面的代码

function myCtrl($state: ng.ui.IStateService){
    // Some code
}

这为我提供了 $state 方法的正确 autocompletion/error 报告。

到目前为止,一切都很好。

问题

当我尝试访问 params 的 属性 时,如下所示

function myCtrl($state: ng.ui.IStateService){
    // Trying to access a property of $state.params
    var example = $state.params.example;
}

我收到一条错误消息:

Property 'example' does not exist on IStateParamsService

因为 quite 是正确的,TypeScript 不知道这个 属性.

我考虑过尝试:

定义我自己的扩展 ng.ui.IStateService

的接口
interface IMyState extends ng.ui.IStateService{
    params: {
        example: string;
    };
}

然后设置类型为myinterface

function myCtrl($state: IMyState){
    var example = $state.params.example;
}

这消除了错误。

$state 的正确类型是什么?

我应该像示例中那样定义自己的界面吗?

使用 Typescript,我们真的可以轻松地扩展合约,UI-Router 。d.ts

所以这是原来的定义(UI-Router d.ts.file):

// a state object
interface IStateService {
    ...
    params: IStateParamsService;
    ...
// params
interface IStateParamsService {
    [key: string]: any;
}

我们可以将这些行引入到我们的自定义中。d.ts这些行

declare module angular.ui
{
    export interface IStateParamsService { example?: string; }
}

这将使我们能够使用 $state 及其参数,例如:

MyMethod($state: ng.ui.IStateService)
{
    let x = this.$state.params.example;
    ...

$state.params 属于 IStateParamsService 类型,如果您查看 the type signature you can read that it is an indexable type.

Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

IStateParamsService描述的类型是

(key: string): any

这意味着类似于 "you can store objects of type any(everything is an any) and read the objects by the key (or index or you-name-it, this is where the name indexable type comes from) of type string"。

这里是一些代码:

// this gives us an object of type IStateParamsService
let params = $state.params;

// params is a indexable type
// we want the object stored at index 'example'
let example = params['example'];
// or
let example = $state.params['example'];

可以找到有关接口和类型的更多信息 here