javascript - 为什么我在我的节点应用程序中没有出现类型错误,尽管我指定了函数参数的类型?
问题描述
我有以下课程
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 代码。
解决方案
如果你想用 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 将在开发过程中向您显示错误:
您还可以使用 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
推荐阅读
- c# - 如何使用 web api 获取 SQL Server 值并转换为 JSON
- visual-studio-code - Visual Studio Code 冻结了我的计算机
- android - 在不同依赖项之间的 values.xml 上 React Native 构建错误重复键
- javascript - 如何使用 Prettier 在代码块之间添加多行?
- linux - 使用 rm 和 ls 时无法通过 SSH 删除目录
- java - 将 CompletableFuture 的结果传递给另一个
- sql - 使用 CASE 语句在 Teradata 中创建新列
- amazon-web-services - Terraform (AWS):如何通过其 ARN 获取负载均衡器的 DNS 名称?
- php - 未捕获的 BadMethodCallException:Object->__call():“页面”上不存在方法“幻灯片”
- tensorflow - 使用数据集 API 训练估计器少于一个时期?