预期打字稿tsc会抛出错误,但没有抛出

时间:2020-03-14 07:38:46

标签: javascript node.js typescript

在用于编辑打字稿代码的IDE中,checkApp.ts中出现警告,指出:

Argument type { someWrongParams: any } is not assignable to parameter type AddAppToListParams.

但是,当我运行tsc时,不会引发任何错误。运行tsc时如何显示错误。

tsconfig.json

{
"compilerOptions": {
    "allowJs": true,
    "noEmit": true,
    "pretty": true,
    "strict": true,
    "strictFunctionTypes": true,
    "noImplicitReturns": true,
    "module": "ES6",
    "target": "ES6"
},
"exclude": [
    "node_modules",
    "dist"
],
"include": [
    "./src/**/*"
]}

代码 checkApp.ts

interface CheckAppParams {
    appId: string;
}

export default (app: any) => async (requestParams: CheckAppParams): Promise<any> => {
    const { appId } = requestParams;
    await app.tasks.addAppToList({ someWrongParams: appId });
};

addAppToList.ts

interface AddAppToListParams {
    appId: string;
}

export default (app: any) => async (requestParams: AddAppToListParams): Promise<any> => {
    const { appId } = requestParams;
    app.list.push(appId);
};

tasks.ts

import checkApp from './checkApp';
import addAppToList from './addAppToList';

export default (app: any) => async (): Promise<any> => {
    app.tasks = {
        addAppToList: addAppToList(app),
        checkApp: checkApp(app),
    };
};

2 个答案:

答案 0 :(得分:1)

tsc在编译问题中显示的代码时不报告错误是正确的。您的期望不正确。

checkApp.ts中,您将导出函数的参数明确定义为(app: any)。因此,在函数内部,app.tasks的类型也是anyapp.tasks.addAppToList的类型也是any,编译器将让您随心所欲。 app.tasks.addAppToList({ someWrongParams: appId });时,编译器没有理由给出错误。

关于您的IDE为何标记错误,问题中没有足够的信息来解释。也许您修改了用于粘贴到此处的代码,但没有保留关键信息。也许您的IDE正在处理与传递给编译器的文件不同的文件。 (我想说这从未发生在我身上,但是有时在大型重构中,我分心了,迷失了轨迹,设法使我的连线越过了一点。)实际上,显示的错误消息确实提示IDE正在使用的代码与问题中显示的代码之间的区别。问题中的代码正在传递类型为{ someWrongParams: string }的参数,但IDE的错误消息抱怨类型为{ someWrongParams: any }的参数。

答案 1 :(得分:1)

如果您想让tsc引发错误,则可以将app定义为interface并引用它而不是any,否则打字稿编译器将不知道它是什么。

将您的应用程序定义为接口将允许编译器识别错误:

export interface App {
  tasks: {
    addAppToList: (requestParams: AddAppToListParams) => Promise<any>;
    checkApp: (requestParams: CheckAppParams) => Promise<any>;
  };
  list: any; // you can make it whatever it needs to be.
}

这种interface的生存能力取决于您对app的使用。 上面的界面只是一个示例,可以是您需要的任何内容。

或者,您可以在运行package.json之前在您的tsc上添加预构建钩子以进行皮棉检查,以检查IDE抛出的警告并阻止tsc运行。您将必须使用与IDE相同的linter规则,但它允许您向构建中添加更严格的检查,而不仅仅是tsconfig.json

中定义的默认打字稿规则集

因此,您以前运行tsc的任何地方都可以使用npm run build来代替tsc

package.json:

  "scripts": {
    "prebuild": "do your lint checks here with can throw errors if you want",
    "build": "tsc"
  },