Typedef in TypeScript error: 'expected variableDeclarator'
Asked Answered
M

3

6

Running tslint on my code I get this error:

expected variableDeclarator: 'getCode' to have a typedef.

for a TypeScript file:

export var getCode = function (param: string): string {
    // ...
};

How do I improve this so I don't see the tslint error?

Mun answered 30/10, 2014 at 13:44 Comment(4)
Have you tried adding a type declaration to getCode? I mean export var getCode : (param: string) => string = function (param: string): string { ... } Dismast
Kuba, that's the correct solution - at least for making tslint happy. However I don't think the code is readable after this. If you add an answer I will accept it as the solution.Mun
Guess I have to withdraw my comment on readability after I have become a little wiser :-)Mun
Okay, added the answer. I wasn't sure if this was the reason, therefore I just posted it as a comment :)Dismast
D
13

You have to explicitely add a type declaration to your variable.

export var getCode : (param: string) => string = function (param: string): string { 
    //...
}

You said this looks pretty unreadable. Well, yes, anonymous types makes TS code look worse, especially when they are huge. In that case, you can declare a callable interface, like this:

export interface CodeGetter {
    (param: string): string;
}

export var getCode: CodeGetter = function(param: string): string { ... }

You can check whether tslint allows you (I can't check it right now) to drop type declaration in definition of the function when using the interface

export interface CodeGetter {
    (param: string): string;
}

export var getCode: CodeGetter = function(param) { ... }
Dismast answered 31/10, 2014 at 9:40 Comment(0)
R
2

Your code fragment looks fine. If this function is made to return a string, it compiles in tsc without an error. Are you sure the return value is a string?

This excerpt is from the tslint repo:

typedef enforces type definitions to exist. Rule options:

"callSignature" checks return type of functions
"indexSignature" checks index type specifier of indexers
"parameter" checks type specifier of parameters
"propertySignature" checks return types of interface properties
"variableDeclarator" checks variable declarations
"memberVariableDeclarator" checks member variable declarations
Rhianna answered 30/10, 2014 at 14:45 Comment(0)
V
1

Add a typedef to getCode:

var getCode: (s: string) => string;

Inline, it should look like this:

export var getCode: (s: string) => string = function (param) {
    // ...
};
Vivian answered 30/10, 2014 at 15:1 Comment(1)
I made tslint stop complaining with a few additions to your suggestion. export var getCode: (s: string) => string = function (param: string): string {//...} This looks really ugly and unreadable, and if that's the answer I prefer removing that tslint check.Mun

© 2022 - 2024 — McMap. All rights reserved.