ES15 has introduced Records and Tuples, So can we use array as a attribute value inside the Record? Can we use object as a value of Tuple index?
1. Is it a valid for Record ?
const user = #{
name: "Avyukt",
age: 39,
hobbies: ['sleeping', 'eating', 'crying'] // Is it a valid add arr
}
2. Is it a valid Tuple?
const user = #[
{ name: "Avyukt", age: 1 }, // Is it valid to add object as a value
{ name: 'Reyansh', age: 5 }
]
2
Answers
This part of the proposed specification:
https://github.com/tc39/proposal-record-tuple/blob/5c9a6e144c687ef5911f4c0c088bc21343cbaf68/README.md?plain=1#L252
No, a tuple may not contain an object, but it can contain a Record, in the current proposal
Likewise, a record may not contain an array value, but it can contain a tuple.
I would caution against the title that ES15 has introduced anything.
This is currently a stage 2 proposal only.
As Adam pointed out in their answer, in the current iteration of the proposed spec you can’t store objects (including arrays) in records or tuples, otherwise you’ll get a TypeError. The way that the spec authors recommend you handle this is to use a
Symbol
in place of your object/array within your record/tuple. TheSymbol
is then used as a key in a Map, allowing you to essentially dereference the symbol by looking up its corresponding value in the Map, for example:Now the above record is valid, since it no longer contains an array, but rather holds a Symbol, and as that’s a primitive it’s allowed.
When reading the value, you would need to dereference the Symbol using the Map, for example: