Skip to content

Accessors should be allowed to be optionalΒ #54240

Open
@justinfagnani

Description

@justinfagnani

Suggestion

Right now accessors are barred from being declared optional. This is a DX regression for decorator users.

πŸ” Search Terms

accessor optional

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Allow accessors to be declared options;

πŸ“ƒ Motivating Example

Decorating a class field should require as few changes over a non-decorated field as necessary. Disallowing accessors from being optional adds an additional change.

Take a plain class:

class A {
  foo?: number;
}

Where you then want to make foo reactive with some library that vends decorators. This would be the change I would expect to make:

import {reactive, Base} from 'some-reactivity-lib';

class A extends Base {
  @reactive
  accessor foo?: number;
}

But 5.0 requires:

import {reactive, Base} from 'some-reactivity-lib';

class A extends Base {
  @reactive
  accessor foo: number | undefined;
}

I don't see a semantic problem with optional accessors. They behave very similar to optional fields (with standard field semantics). With useDefineForClassFields and this example:

class C {
  accessor foo?: number;
  
  bar?: number;
}

both foo and bar would exist on the runtime object even though they're optional, ie 'foo' in c === 'bar' in c.

πŸ’» Use Cases

More ergonomic decorator usage.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions