[英]Typescript not triggering errors for an uninitialized object property named "name"
I've found some weird behavior on a Typescript code that I'm writing.我在我正在编写的 Typescript 代码上发现了一些奇怪的行为。
Typescript playground link 打字稿游乐场链接
Somehow Typescript does not trigger an error for an not initialized property if that property name is name
:不知何故,如果属性名称是
name
,Typescript 不会为未初始化的属性触发错误:
What is this?这是什么? Is this a bug or what?
这是错误还是什么?
This is the error for the value
property:这是
value
属性的错误:
No value exists in scope for the shorthand property 'value'.
速记属性“值”的范围内不存在任何值。 Either declare one or provide an initializer.(18004)
要么声明一个,要么提供一个初始化程序。(18004)
interface INTERFACE_A {
name: string, // ALSO TRIED WITH OTHER TYPES. SAME RESULT
}
function fooA(x: INTERFACE_A): INTERFACE_A { return x; }
fooA({
name // THIS SHOULD BE AN ERROR (BUT IT'S NOT)
});
const objA: INTERFACE_A = {
name // THIS SHOULD BE AN ERROR (BUT IT'S NOT)
}
interface INTERFACE_B {
value: string
}
function fooB(x: INTERFACE_B): INTERFACE_B { return x; }
fooB({
value // THIS IS AN ERROR (OK)
});
const objB: INTERFACE_B = {
value // THIS IS AN ERROR (OK)
}
This doesn't seem to be related to the Typescript Playground, since it's also happening in my VSCode dev environment:这似乎与 Typescript Playground 无关,因为它也在我的 VSCode 开发环境中发生:
UPDATE:更新:
This is probably related to the window.name
property, which is of type string
.这可能与
string
类型的window.name
属性有关。 But it still behaves differently than window.innerWidth
, for example:但它的行为仍然与
window.innerWidth
不同,例如:
See that TS complains if I use innerWidth
as a string
, but it does not complain when I try to use window.name
as a number
:如果我使用
innerWidth
作为string
,TS 会抱怨,但是当我尝试使用window.name
作为number
时它不会抱怨:
{ name }
is shorthand for { name: name }
, window.name
is built-in property, and properties of window
are global in browsers, so name
is a global property that's equivalent to window.name
. { name }
是{ name: name }
简写, window.name
是内置属性, window
属性在浏览器中是全局的,所以name
是一个全局属性,相当于window.name
。
In effect, your code is doing this:实际上,您的代码正在执行以下操作:
fooA({
name: window.name
})
and that's totally valid (although probably not what you wanted).这是完全有效的(虽然可能不是你想要的)。
For a solution to this kind of error, ESLint can be configured to give errors when you use browser globals like name
without an explicit reference to the window object ( window.name
)对于此类错误的解决方案,ESLint 可以配置为在您使用浏览器全局变量(如
name
而不显式引用 window 对象( window.name
)时出现错误
no-restricted-globals
packageno-restricted-globals
包.eslintrc.js
:.eslintrc.js
的规则中:module.exports = {
// ... other fields omitted
rules: {
// ... other rules omitted
"no-restricted-globals": ["error"].concat(
require("confusing-browser-globals")
),
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.