小编典典

打字稿命名参数像在angularjs中使用?

angularjs

我正在尝试学习打字稿和angularjs(因此我是JavaScript的菜鸟)

通过angularjs教程,我看到他们做了这样的事情:

在普通的javascript中:

    //for full example, see the "Wire up a backend" project.js example 
//on the main page of http://angularjs.org 
            function CreateCtrl($scope, $location, Project){
        //do stuff
        }

更重要的是,这些参数可以按任何顺序排列(或根本不按顺序排列),而Project实际上是用户定义的变量/类型。angularjs框架能够将参数映射到实际对象。

那么现在到Typescript,我该如何重新创建这种类型的功能?我实际上想以某种方式描述angularjs的行为,以便将其包装在打字稿中(强烈键入此灵活的属性注入)

有任何想法吗?


阅读 257

收藏
2020-07-04

共1个答案

小编典典

在“绝对类型”上有一个AngularJS类型定义,可让您使用TypeScript中的Angular。

如果我正在为这样的现有函数创建一个定义(在没有命名参数的情况下),那么我可能会以特定的顺序定义它们(即使我知道它们 可以
在纯JavaScript中以不同的顺序传递)或创建一组与我想公开的可能性相匹配的函数重载,如下所示:

interface Example {
    ($scope: bool, $location: string, Project: number): void;
    ($location: string, $scope: bool, Project: number): void;
    (Project: number, $scope: bool, $location: string): void;
}

declare var example: Example;

当我尝试调用时,example(我会通过三个选项获得智能感知;如果不使用这些组合之一,则会收到编译器警告。

在JavaScript中,命名参数通常是用一个对象创建的,因此,如果我正在编写一个可以以这种方式接受参数的新方法,我会这样做。

interface ExampleArguments {
    scope: bool;
    location: string;
    project: number;
}

var example = function (exampleArguments: ExampleArguments) {

};

example({ scope: true, project: 4, location: 'hi' });

它是在TypeScript中静态键入和检查的。

2020-07-04