Recently, while working on a project with Svelte 3, I encountered this interesting piece of code:
REPL:
<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
Interestingly, Typescript raised an error in my case:
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)
However, when I modified the code to const player = "bob"
, everything started working fine. It's quite intriguing!
Ever wondered why?