我有一节课
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
}我想知道我要做什么,这样才能使类中不存在的键被标记为错误。我正在使用代码。
发布于 2020-11-09 11:13:34
您需要使用一种进行类型检查的语言或工具。仅仅在评论中添加{Order}并不能起到任何作用。您必须有一些工具来理解JSDoc格式并检查代码。JavaScript本身( A)完全忽略注释,而B)不提供任何解析/编译时类型检查。一个这样的工具是打字机,一个ESLint插件。(不是背书,我从未使用过。) 杰门东指出,VSCode本身可以用现有的JSDoc类型注释为您做这件事(这似乎很酷)。
如果您想要类型安全,现在非常流行的选择是使用TypeScript。TypeScript是JavaScript的一个类型化超集,它编译为JavaScript。下面是打字本中的代码:
class Order {
    id: number;
    constructor(id: number) {
       this.id = id;
    }
}
// ...elsewhere...
async function doSomething(order: Order) {
   console.log(order.ids);
}不过,还有其他选项,如流。
类部分也可以这样编写,在功能上与上面的版本相同:
class Order {
    constructor(public id: number) {
    }
}将public放在构造函数参数前面告诉TypeScript,它应该创建一个与参数同名的公共属性,并在构造函数中自动生成代码,以便将参数的值分配给属性。
https://stackoverflow.com/questions/64750499
复制相似问题