skip to Main Content

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


  1. This part of the proposed specification:

    https://github.com/tc39/proposal-record-tuple/blob/5c9a6e144c687ef5911f4c0c088bc21343cbaf68/README.md?plain=1#L252

    Records and Tuples may only contain primitives and other Records and Tuples. Attempting to create a Record or Tuple that contains an Object (null is not an object) or a Function throws a TypeError.

    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.

    Login or Signup to reply.
  2. 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. The Symbol 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:

    const RefsRegistry = new WeakMap(); 
    const hobbiesRef = Symbol("hobbies");
    
    RefsRegistry.set(hobbiesRef, ['sleeping', 'eating', 'crying']); // ECMAScript 2023 (ES14) now allows for Symbols in WeakMaps
    
    const user = #{
      name: "Avyukt",
      age: 39,
      hobbies: hobbiesRef
    };
    

    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:

    const hobbies = RefsRegistry.get(user.hobbies);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search