微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

3.1 之后的 TypeScript 不接受回调函数参数类型

如何解决3.1 之后的 TypeScript 不接受回调函数参数类型

我对 jQuery Terminal 有这个问题。我有相当大的 d.ts 文件,但它不能正常工作我试图更新依赖项,但一切都坏了。有一段时间我无法更新 TypeScript,因为遇到了这种类型的错误(3.1 之后的版本)

./node_modules/.bin/tsc --noEmit --project tsconfig.json
test.ts:18:31 - error TS7006: Parameter 'command' implicitly has an 'any' type.

18 $('.term').terminal([function(command,term) {

即使是回调函数也定义了类型。

我已经检查了 TypeScript playground,这很好用:

type arg = ((x: number) => number) | number;
function hey(list: arg[]) {
  list.forEach(x => {
    if (typeof x === 'function') {
      x(10);
    }
  });
}

hey([10,function(x) { x.toFixed(10); return x }]);

当我使用 hey 时,我有没有类型的函数,类型取自我的回调定义。任何人都知道为什么会发生这种情况以及如何解决它? 问题是,当我不更新打字稿时,我从 babel_traverse 得到了错误,就像打字稿一样,根本没有对代码进行类型检查,打字稿中出现了数千个关于无效语法的错误,请参阅:Angular: node_modules/@types/babel _traverse/index.d.ts(1137,43): error TS1109: Expression expected

如果您不知道答案,也许您知道如何调试我的打字稿 d.ts 文件,以便我自己找到问题。

编辑:

这是类型声明的一部分:

type TypeOrArray<T> = T | T[];
declare namespace JQueryTerminal {
    type interpreterFunction = (this: JQueryTerminal,command: string,term: JQueryTerminal) => any;
    type terminalObjectFunction = (...args: (string | number | RegExp)[]) => (void | TypeOrPromise<echovalue>);
    type Interpreter = string | interpreterFunction | ObjectInterpreter;
    type ObjectInterpreter = {
        [key: string]: ObjectInterpreter | terminalObjectFunction;
    }   
}

interface JQuery<TElement = HTMLElement> {
    terminal(interpreter?: TypeOrArray<JQueryTerminal.Interpreter>,options?: TerminalOptions): JQueryTerminal;
}

问题是这在以前版本的 TypeScript 中运行良好。

这是我的tsconfig.json

{
    "compilerOptions": {
        "target": "es6","module": "commonjs","strict": true,"lib": ["es2015","ES2018.Promise","dom"]
    },"exclude": ["npm"]
}

我在 test.ts 中有这个检查 CI 中的类型:

/// <reference path="./js/jquery.terminal.d.ts" />

import "jquery";
import "jquery.terminal";


function test_type<T>(x: T) {};

// this works
$('.term').terminal(function(command,term) {
    term.echo(command);
});
// this also works
$('.term').terminal(function(command) {
    this.echo(command);
});
// this doesn't work,function in array
$('.term').terminal([function(command,term) {
    term.echo(command);
    return Promise.resolve(document.createElement('div'));
}]);

解决方法

用显式函数重载替换 TypeOrArray 似乎解决了这个问题:

interface JQuery<TElement = HTMLElement> {
   terminal(interpreter?: JQueryTerminal.Interpreter): any;
   terminal(interpreter?: JQueryTerminal.Interpreter[]): any;
}

TS playground

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。