打字稿命名参数像在angularjs中使用? [英] typescript named parameters like used in angularjs?

查看:72
本文介绍了打字稿命名参数像在angularjs中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试同时学习打字稿和angularjs(因此我是一个菜鸟,因此也学习了javascript)

I'm trying to learn both typescript and angularjs (and thus javascript as i'm a noob)

在整个angularjs教程中,我看到他们做了这样的事情:

going through the angularjs tutorials, I see they do stuff like this:

在普通javascript中:

in normal 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框架能够将参数映射到实际对象.

the kicker is, those parameters could be in any order (or not there at all), and Project is actually a user defined variable/type. The angularjs framework is able to map the parameters to actual objects.

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

So now to Typescript, how can I recreate this type of functionality? I actually would like to describe angularjs's behavior in some way to let me wrap it in typescript, (strongly type this flexible property injection)

有什么想法吗?

推荐答案

有一个 AngularJS绝对类型上的类型定义,可让您从TypeScript中使用Angular.

There is an AngularJS type definition on Definitely Typed that lets you use Angular from TypeScript.

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

If I was creating a definition for an existing function such as this (in the absence of named arguments), I would probably either define them in a specific order (even though I know they could be passed in varying orders in plain JavaScript) or create a set of function overloads that matched the possibilities I wanted to expose, like this:

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(时,我得到了三个选项的智能感知,如果我不使用这些组合之一,则会收到编译器警告.

When I attempt to call example( I get intellisense with the three options and if I don't use one of these combinations I get a compiler warning.

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

In JavaScript, named arguments are normally created with an object, so if I was writing a new method that could accept arguments in this way I would do this...

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

var example = function (exampleArguments: ExampleArguments) {

};

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

使用TypeScript静态键入并检查的类型.

Which is statically typed and checked in TypeScript.

这篇关于打字稿命名参数像在angularjs中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆