gpt4 book ai didi

javascript - Typescript 未触发名为 "name"的未初始化对象属性的错误

转载 作者:行者123 更新时间:2023-12-02 10:52:31 25 4
gpt4 key购买 nike

我在我正在编写的 Typescript 代码中发现了一些奇怪的行为。
Typescript playground link
如果属性名称为 name,Typescript 不会以某种方式触发未初始化属性的错误。 :
enter image description here
这是什么?这是一个错误还是什么?
这是 value 的错误。属性(property):

No value exists in scope for the shorthand property 'value'. Either declare one or provide an initializer.(18004)


enter image description here
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)
}
这似乎与 Typescript Playground 无关,因为它也发生在我的 VSCode 开发环境中:
enter image description here
enter image description here
更新:
这可能与 window.name 有关属性,类型为 string .但它的行为仍然不同于 window.innerWidth , 例如:
如果我使用 innerWidth,请查看 TS 提示作为 string ,但是当我尝试使用 window.name 时它不会提示作为 number :
Typescript playground link
enter image description here
enter image description here

最佳答案

{ name }{ name: name } 的简写, window.name是内置属性,window 的属性在浏览器中是全局的,所以 name是一个全局属性,相当于 window.name .
实际上,您的代码正在执行此操作:

fooA({
name: window.name
})
这是完全有效的(尽管可能不是你想要的)。

关于javascript - Typescript 未触发名为 "name"的未初始化对象属性的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64062788/

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