typescript - Svelte 3,如果我使用响应式语句,为什么不能访问这个 javascript 对象属性?
问题描述
我将此代码与 Svelte 3 一起使用:
REPL:https ://svelte.dev/repl/bf73fffc1b9442dfbcd492eaa9c048e1?version=3.35.0
<script lang="ts">
const players = {
men: {
john: "high",
bob: "low",
},
};
// const player = "bob"
$: player = "bob";
const test = players.men[player];
console.log(test); //prints undefined
</script>
{player} //bob
{test} //undefined
打字稿甚至告诉我:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ john: string; bob: string; }'.
No index signature with a parameter of type 'string' was found on type '{ john: string; bob: string; }'.ts(7053)
如果我使用const player = "bob"
它就可以了!
为什么?
解决方案
您不能使用随机字符串安全地访问对象,这就是编译器抱怨的原因。使用时它不会抱怨的原因const
是常量字符串文字在编译时已知,并且在运行时无法更改,因此编译器知道它是安全的。有几种方法可以解决这个问题,但最简单(NB 不是最安全)的方法是强制转换:
const players = {
men: {
john: "high",
bob: "low",
},
};
// const player = "bob"
let player = "bob";
const test = players.men[player as keyof typeof players.men];
可能还存在一种更安全的方法来使用您尝试使用的 Svelte 东西来执行此操作,通常在 TS 中编写此类内容时,我将使用字符串文字或枚举让编译器确保我没有得到意外undefined
:
enum Males {
JOHN = "john",
BOB = "bob"
}
const players: {
men: {
[key in Males]: string;
}
} = {
men: {
john: "high",
bob: "low",
},
};
const test2 = players.men[Males.JOHN];
推荐阅读
- angular - 如何在 Angular 5 中创建单例服务?
- c++ - C++ 回溯排列
- ios - 在不影响导航栏的情况下更改 NavigationController 的内容视图宽度
- leaflet - wkhtmltopdf 和传单等待地图
- javascript - 扩展 Array 的原型不在打字稿中构建
- asp.net-mvc - Asp .Net core 2.0 的剑道 UI?
- dc.js - dc.js rowChart,条形图从右到左
- reactjs - 如何使用 Ant Design 的响应式 Sider 避免内容重排
- .net - Listview 上的嵌套对象似乎被垃圾收集,没有收到更改属性的通知
- rust - 什么是非词汇生命周期?