jsdom / webidl2js

Auto-generate JS class structures for Web IDL specifications
MIT License
79 stars 30 forks source link

Return `null` instead of `undefined` from nullable attribute #264

Closed cdoublev closed 1 year ago

cdoublev commented 1 year ago

In an instance of a wrapper class, the getter of an attribute whose definition is a type qualified with ? (nullable type), returns undefined instead of null, as defined in the Web IDL spec:

A nullable type is an IDL type constructed from an existing type (called the inner type), which just allows the additional value null to be a member of its set of values.

https://webidl.spec.whatwg.org/#idl-nullable-type

I guess it can be fixed by appending ?? null to getterBody in https://github.com/jsdom/webidl2js/blob/90ba8b1139baece4929944b81f08a588c8a6dc81/lib/constructs/attribute.js#L45, but there seems to be many occurrences and you surely know how to fix it quickly and properly, if there are no reason for returning undefined that I am not aware of.

TimothyGu commented 1 year ago

We typically rely on the impl class to implement attribute getters properly. We can’t do what you suggest in the general case, since any? (or even undefined?) contains both null and undefined.

cdoublev commented 1 year ago

I suspected there is a reason, thanks. Too bad because given this interface:

interface Foo {
  string? attribute bar;
}

the implementation requires:

class FooImplementation {
  constructor(globalObject, { bar }) {
    this._bar = bar
  }
  get bar() {
    return this._bar ?? null
  }
}

instead of:

class FooImplementation {
  constructor(globalObject, { bar }) {
    this.bar = bar
  }
}

There are a number of cases in CSS. I read in the Web IDL spec that the inner type of a nullable cannot be any.

Please let me know if useNullAsFallback = this.idl.idlTpe.nullable && this.idl.idlType.idlType !== 'undefined' can be an option.