Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

typescript named parameters like used in angularjs?

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

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

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
        }

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.

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)

any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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;

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.

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' });

Which is statically typed and checked in TypeScript.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...