webidl icon indicating copy to clipboard operation
webidl copied to clipboard

`record<unsigned short, ...`

Open beaufortfrancois opened this issue 4 years ago • 5 comments

Hey folks, I read that record type keys must be one of DOMString, USVString, or ByteString. Would it be possible to consider unsigned short as well or is there another way to think about this?

Here's what I'd like to implement.

dictionary Foo {
  ...
  record<unsigned short, Bar> someName;
}; 

dictionary Bar {
  BufferSource someSource;
  BufferSource anotherSource;
};

Thanks in advance, Francois.

beaufortfrancois avatar Apr 20 '21 08:04 beaufortfrancois

JavaScript objects don't have numeric keys. This has come up before, so maybe we should add a note pointing to https://heycam.github.io/webidl/#es-record.

annevk avatar Apr 20 '21 08:04 annevk

This JS code seems equivalent to what I need. Am I misunderstanding it?

const o = { 0x0001: 'hello', 0x0002: 'world' };
-> {1: "hello", 2: "world"}

beaufortfrancois avatar Apr 20 '21 08:04 beaufortfrancois

JS syntax permits “bare” number tokens without expression-enclosing brackets and bare strings without quotes if they are valid identifiers, but both are effectively shorthand — an ES property key is a string or symbol and any other value gets coerced:

const o = ({ [{ toString: () => '1' }]: 'hello', [2n]: 'world' });
-> {1: "hello", 2: "world"}

[ Reflect.ownKeys(o)[0], typeof Reflect.ownKeys(o)[0] ];
-> [ "1", "string" ]

(More info:)

Here’s where numeric literals get evaluated in an object literal to become a property key:

LiteralPropertyName : NumericLiteral

  1. Let nbr be the NumericValue of NumericLiteral.
  2. Return ! ToString(nbr).

ES does have a concept of integer index and array index property keys — strings which are canonical numeric index strings in one of two ranges. That concept is used to determine the property-related behaviors of some exotic objects (arrays and typed arrays). (Maybe there’s an avenue there?)

bathos avatar Apr 20 '21 09:04 bathos

Thank you @bathos for the detailed explanation.

Do you have folks some idea on how to move forward? Without record<unsigned short, ... support, I'm currently going with a sequence of dictionary with a key instead. There may be a better way...

dictionary Foo {
  ...
  sequence<Bar> someName;
}; 

dictionary Bar {
  required unsigned short someKey;
  BufferSource someSource;
  BufferSource anotherSource;
};

beaufortfrancois avatar Apr 21 '21 06:04 beaufortfrancois

Following https://whatwg.org/faq#adding-new-features would help. 😊

annevk avatar Apr 21 '21 06:04 annevk