网站搜索

javascript - 在 'use strict' 之后寻找 'use stricter'


所以我总是在我的 JavaScript 代码中使用 'use strict',但我被自己犯的一个愚蠢错误绊了一下。虽然 'use strict' 会检查那些没有用 const 或 let 定义的变量,但它不会对对象的键做同样的检查。所以,我做了如下操作:

'use strict';

let foo = {
    update: ''
};

// and much later in the code
foo['udpate'] = 'This is what I have been working on lately';

不用说,在处理了大约30万个文件之后,我得到的结果完全不对,而且不知道原因。

那么,我本可以做些什么来让 JS 警告我呢?我现在应该迁移到 TypeScript 吗?TS 会防止这种错误吗?

答案#1

是的,TypeScript 在这里会有所帮助,尽管正如 Brad 在评论中指出的那样,这并不是解决问题的唯一方法。

Typescript 通过 结构化类型 来工作。如果你给 foo 添加类型,它会告诉你 update 字段缺失:

let foo: UpdateHolder = {  // Fails because UpdateHolder is missing the property "update".
    udpate: 'This is what I have been working on lately'
};

如果你不为 foo 添加类型,当你尝试将 foo 分配给期望 UpdateHolder 的方法时,它将会失败:

let foo = {  // Succeeds.
    udpate: 'This is what I have been working on lately'
};

processUpdate(foo);  // Fails because foo is not assignable to UpdateHolder;
                     // this is because it's missing the "update" property.

// This assumes that elsewhere processUpdate is defined as:
function processUpdate(updateHolder: UpdateHolder);
// or:
function processUpdate(updateHolder: {update: string});

然而,由于 Javascript 是一种灵活的语言,Typescript 不会为你验证 foo 没有其他属性。它只会检查正确的属性是否存在,而不一定检查不正确的属性是否不存在。