Corey Alix
Corey Alix

Reputation: 2750

Can TypeScript (d.ts) describe an anonymous method with typed args?

Why would ITreeArgs not exist in the export function definition (tree.d.ts file)?

interface ITreeArgs {
    mayHaveChildren: bool;
}

export function(args: ITreeArgs); <- The name 'ITreeArgs' does not exist in the current scope

these both work:

export function c(args: ITreeArgs); <- adding name works!
export function (args); <- removing type works!

Upvotes: 0

Views: 1912

Answers (3)

Anatoly Bakirov
Anatoly Bakirov

Reputation: 21

I do it like this (in dojo.d.ts file):

module "dojo/on" {
    function (target: Element, type: string, listener: (e: Event) => void);
}

Then I import it like this:

import on = module("dojo/on");

And use this module as pure function like this:

on(this.goButton, "click", this.ongo.bind(this));

Upvotes: 2

Fenton
Fenton

Reputation: 251062

You need to give your function a name for it to be valid syntax - this is the real error.

ITreeArgs is available as adding a name shows.

interface ITreeArgs {
    mayHaveChildren: bool;
}

export function functionName(args: ITreeArgs) {
    //function body
}

I'm not sure what your reason is for wanting to leave out the function name?

Update: to declare a constructor on an interface, you use:

interface ITreeArgs {
    new (myArg: string);
}

To declare a constructor on a class in a definition file, you would use:

declare class MyClass {
     constructor(myArg: ITreeArgs);
}

It is not possible to declare a constructor on a module.

In the language specification, it says that you can leave out the declare keyword in a .d.ts file - but in practice I find that it makes things absolutely clear if someone hasn't spotted the file extension.

Upvotes: 1

Dima Vidmich
Dima Vidmich

Reputation: 1375

name requirement is for export only because Typescript will add code

namespace.function_name = ...

so this is unclear why somebody wants to export something anonymously :)

but for example if you want return typed anonymous function from another function you can do it.

function foo() {
    return function(bar:string):string { return bar; }
}

Upvotes: 0

Related Questions