Why this code produces an error Type 'symbol' cannot be used to index type '{ [x: string]: string; }'.
:
let symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj
// ^^^^^ the error is here
console.log(alias)
And most importantly, how do I fix this?
TypeScript casting a destructured object typeconst {firstname: string, age: number} = user; But this assigns the firstname variable to be string and the age variable to be called number . And when we introduce two of the same type, we are hit with an error since we are redefining a variable.
symbol values are created by calling the Symbol constructor. Symbols are immutable, and unique. Just like strings, symbols can be used as keys for object properties. Symbols can also be combined with computed property declarations to declare object properties and class members.
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
In JavaScript, destructuring is when you decompose the properties of an object or the indexes of an array to separate them to create specific variables. This does not mean that these separated objects or arrays can never be used again in the program.
The cool part about TypeScript is that we can define types for certain variables. However, there is a scenario that might prove a bit difficult. And this is destructuring an object. By using this destructuring, we extract specific properties from an object.
The type can either be specified inline, or from an existing interface, type declaration, or by using type assertions. Ideally, you should correctly type the object wherever possible because if the object itself has a type declaration, then TypeScript would infer those types automatically when you're destructuring an object.
Typing Destructured Object Parameters in TypeScript November 13, 2015 In TypeScript, you can add a type annotation to each formal parameter of a function using a colon and the desired type, like this: function greet(name: string) { return `Hello $ {name}!`; }
The TypeScript compiler complains that it can't find the name pretty that is used within the function body. This is because boolean is not a type annotation in this case, but the name of the local variable that the value of the pretty property gets assigned to. Again, this is part of the specification of how object destructuring works.
You just need to declare the symbol
as const
to make the compiler infer a literal type for it and not the general Symbol
type.
const symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj
console.log(alias)
This PR might be useful as to when typescript infers a unique symbol
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With