18

I'm trying to learn both TypeScript and Angular (and thus JavaScript).

Going through the Angular tutorials, I see they do stuff like this:

In normal javascript:

function CreateCtrl($scope, $location, Project){
// do stuff
}

For full example, see the "Wire up a backend" project.js example on the Angular homepage.

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 Angular framework is able to map the parameters to actual objects.

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

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

basically it sounds like you are saying "no, you can't do it". is that right? i use angularjs d.ts and that doesn't help. also, your bottom example, angular's framework does the calling, so i don't have any control over that. maybe typescript doesn't have any way of handling this right now huh.
Named arguments were proposed, but rejected from the TypeScript language specification - so it isn't possible to allow exactly as you describe - but you can formalise it so they are in a fixed order and get what you want (even though Angular would accept any order). typescript.codeplex.com/workitem/256

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.