5

在我的代码上运行 tslint 我得到这个错误:

expected variableDeclarator: 'getCode' to have a typedef.

对于 TypeScript 文件:

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

我该如何改进这个,所以我看不到 tslint 错误?

4

3 回答 3

12

您必须明确地向变量添加类型声明。

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

你说这看起来很难读。嗯,是的,匿名类型使 TS 代码看起来更糟,尤其是当它们很大时。在这种情况下,您可以声明一个可调用接口,如下所示:

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

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

您可以检查 tslint 是否允许您(我现在无法检查)在使用接口时在函数定义中删除类型声明

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

export var getCode: CodeGetter = function(param) { ... }
于 2014-10-31T09:40:11.753 回答
2

您的代码片段看起来不错。如果这个函数返回一个字符串,它会在 tsc 中编译而不会出错。你确定返回值是一个字符串吗?

这段摘录来自 tslint 仓库:

typedef 强制类型定义存在。规则选项:

"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
于 2014-10-30T14:45:31.847 回答
1

将 typedef 添加到 getCode:

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

内联,它应该如下所示:

export var getCode: (s: string) => string = function (param) {
    // ...
};
于 2014-10-30T15:01:57.143 回答