首页 > 解决方案 > 为什么我在我的节点应用程序中没有出现类型错误,尽管我指定了函数参数的类型?

问题描述

我有以下课程

class Order {
    constructor(id){
       this.id=id;
    }
}

以及一个将订单作为参数的函数:

/** 
 * @param {Order} order
*/
async function doSomething(order){
  // the problem is now that I can type something like that
   console.log(order.ids) // the key ids does not exist on the class Order but still no error
}

我想知道我必须做什么才能将类中不存在的键标记为错误。我正在使用 Visual Studio 代码。

标签: javascriptnode.jsclass

解决方案


如果你想用 typescript 对.js文件进行类型检查,你需要添加// @ts-check到你的代码中。

例如:

// @ts-check

class Order {
    constructor(id){
       this.id=id;
    }
}

/** 
 * @param {Order} order
*/
async function doSomething(order){
   console.log(order.ids) // the key ids does not exist on the class Order but still no error
}

现在 Visual Studio Code 将在开发过程中向您显示错误:

TSCheck VsCode

您还可以使用 typescript cli 以编程方式测试您的代码:

npx typescript --noEmit --allowJs index.js

  npx: installed 1 in 1.344s
  index.js:13:22 - error TS2339: Property 'ids' does not exist on type 'Order'.

  13    console.log(order.ids) 
                          ~~~


  Found 1 error.

详见:https ://www.typescriptlang.org/docs/handbook/intro-to-js-ts.html


推荐阅读