0

我对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 操场,这工作正常:

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 收到错误,例如 TypeScript 不要对代码进行类型检查,打字稿出现数千个无效语法错误,请参阅:Angular: node_modules/@types/babel _traverse/index .d.ts(1137,43):错误 TS1109:预期表达式

如果您不知道答案,也许您知道如何调试我的 typescript 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'));
}]);
4

1 回答 1

1

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

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

TS游乐场

于 2020-12-22T09:07:00.350 回答