gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:39 25 4
gpt4 key购买 nike

所以我总是在我的 JavaScript 代码中“使用严格”,但我犯了一个愚蠢的错误。虽然 'use strict' 捕获未使用 constlet 定义的变量,但它不会对对象键执行相同的操作。所以,我做了以下事情:

'use strict';

let foo = {
update: ''
};

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

不用说,在处理了大约 300,000 个文件后,我得到的结果有很大偏差,而且不知道为什么。

那么,我应该怎么做才能让 JS 警告我?我现在应该迁移到 TypeScript 吗? TS 会阻止这样的错误吗?

最佳答案

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

Typescript 通过 structural typing 工作.如果您向 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 没有其他属性。它只会检查是否存在正确的属性,不一定会检查是否存在不正确的属性。

关于javascript - 在 'use strict' 之后寻找 'use stricter',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com