Skip to content

Instantly share code, notes, and snippets.

@littledan
Last active August 2, 2023 16:45
Show Gist options
  • Save littledan/c10bf2a0309a02330cb4ef931daef103 to your computer and use it in GitHub Desktop.
Save littledan/c10bf2a0309a02330cb4ef931daef103 to your computer and use it in GitHub Desktop.
Decorators: yet another proposal (very early draft, will change)

Decorators: yet another proposal

Introduction

Decorators are a proposal for extending JavaScript classes which is widely adopted among developers in transpiler environments, with broad interest in standardization. TC39 has been iterating on decorators proposals for over five years. This document describes a new proposal for decorators based on elements from all past proposals.

Decorators @decorator are functions called on class elements or other JavaScript syntax forms during definition, potentially wrapping or replacing them with a new value returned by the decorator.

A decorated class field is treated as wrapping a getter/setter pair for accessing that storage. Decorated storage is useful for observation/tracking, which has been a pain point for the original legacy/experimental decorators combined with [[Define]] semantics for class fields. These semantics are based on Michel Weststrate's "trapping decorators" proposal.

Decorators may also annotate a class element with metadata. These are simple, unrestricted object properties, which are collected from all decorators which add them, and made available as a set of nested objects in the [Symbol.metadata] property.

By making decorators always simply wrap what they are decorating, rather than performing other transformations, this proposal aims to meet the following requirements:

  • The class "shape" is visible without executing the code, making decorators more optimizable for engines.
  • Implementations can work fully on a per-file basis, with no need for cross-file knowledge.
  • No new namespace or type of second-class value is added--decorators are functions.

Examples

A few examples of how to implement and use decorators in this proposal:

@logged

The @logged decorator logs a console message when a method starts and finishes. Many other popular decorators will also want to wrap a function, e.g., @deprecated, @debounce, @memoize, etc.

Usage:

import { logged } from "./logged.mjs";

class C {
  @logged
  m(arg) {
    this.#x = arg;
  }

  @logged
  set #x(value) { }
}

new C().m(1);
// starting m with arguments 1
// starting set #x with arguments 1
// ending set #x
// ending m

@logged can be implemented in JavaScript as a decorator. Decorators are functions that are called with an argument containing what's being decorated. For example:

  • A decorated method is called with the method being decorated
  • A decorated getter is called with the getter function being decorated
  • A decorated setter is called with the setter function being decorated

(Decorators are called with a second parameter giving more context, but we don't need those details for the @logged decorator.)

The return value of a decorator is a new value that replaces the thing it's wrapping. For methods, getters and setters, the return value is another function to replace that method, getter or setter.

// logged.mjs

export function logged(f) {
  const name = f.name;
  function wrapped(...args) {
    console.log(`starting ${name} with arguments ${args.join(", ")}`);
    const ret = f.call(this, ...args);
    console.log(`ending ${name}`);
    return ret;
  }
  wrapped.name = name;
  return wrapped;
}

This example roughly "desugars" to the following (i.e., could be transpiled as such):

let x_setter;

class C {
  method(arg) {
    this.#x = arg;
  }

  static #x_setter(value) { }
  static #_ = (x_setter = C.#x_setter, void 0);
  set #x(value) { return x_setter.call(this, value); }
}

C.prototype.method = logged(C.prototype.method, { kind: "method", name: "m", isStatic: false });
x_setter = logged(x_setter, {kind: "setter", isStatic: false});

Note that getters and setters are decorated separately. Accessors are not "coalesced" as in earlier decorators proposals (unless they are generated for a field; see below).

@defineElement

HTML Custom Elements lets you define your own HTML element. Elements are registered using customElements.define. Using decorators, the registration can happen up-front:

import { defineElement } from "./defineElement.mjs";

@defineElement('my-class')
class MyClass extends HTMLElement { }

Classes can be decorated just like methods and accessors. The class shows up in the value option.

// defineElement.mjs
export function defineElement(name, options) {
  return klass => { customElements.define(name, klass, options); return klass; }
}

The decorator takes arguments at its usage site, so it is implemented as a function that returns another function. You can think of it as a "decorator factory": after you apply the arguments, it gives you another decorator.

This decorator usage could be desugared as follows:

class MyClass extends HTMLElement { }
MyClass = defineElement(MyClass, {kind: "class"});

Decorators adding metadata

Decorators can add metadata about class elements by adding a metadata property of the context object that is passed in to them. All of the metadata objects are Object.assign'ed together and placed in a property reachable from [Symbol.metadata] on the class. For example:

@annotate({x: "y"}) @annotate({v: "w"}) class C {
  @annotate({a: "b"}) method() { }
  @annotate({c: "d"}) field;
}

C[Symbol.metadata].class.x                     // "y"
C[Symbol.metadata].class.v                     // "w"
C[Symbol.metadata].prototype.methods.method.a  // "a"
C[Symbol.metadata].instance.fields.field.c     // "d"

NOTE: The exact format of the annotations object is not very well-thought-out and could use more refinement. The main thing I'd like to illustrate here is, it's just an object, with no particular support library to read or write it, and it's automatically created by the system.

This decorator @annotate could be implemented as follows:

function annotate(metadata) {
  return (_, context) => {
    context.metadata = metadata;
    return _;
  }
}

Each time a decorator is called, it is passed a new context object, and after each decorator returns, the context object's metadata property is read, and if it's not undefined, it's included in the [Symbol.metadata] for that class element.

Note that, since metadata is held on the class, not on the method, the metadata is not visible to earlier decorators. Metadata on classes is added to the constructor after all class decorators have run so that they are not lost by later wrapping.

@tracked

The @tracked decorator watches a field and triggers a render() method when the setter is called. This pattern, or patterns like it, is common in frameworks to avoid extra bookkeeping scattered throughout the application to ask for re-rendering.

Decorated fields have the semantics of getter/setter pairs around an underlying piece of private storage. The decorators can wrap these getter/setter functions. @tracked can wrap this getter/setter pair to implement the re-rendering behavior.

import { tracked } from "./tracked.mjs";

class Element {
  @tracked counter = 0;

  increment() { this.counter++; }

  render() { console.log(counter); }
}

const e = new Element();
e.increment();  // logs 1
e.increment();  // logs 2

When fields are decorated, the "wrapped" value is an object with two properties: get and set functions that manipulate the underlying storage. They are built to be .call()ed with the instance of the class as a receiver. The decorator can then return a new object of the same form. (If one of the callbacks is missing, then it is left in place unwrapped.)

// tracked.mjs

export function tracked({get, set}) {
  return {
    get,
    set(value) {
      if (get.call(this) !== value) {
        set.call(this, value);
        this.render();
      }
    }
  };
}

This example could be roughly desugared as follows:

let initialize, get, set;

class Element {
  #counter = initialize(0);
  get counter() { return this.#counter; }
  set counter(v) { this.#counter = v; }

  increment() { this.counter++; }

  render() { console.log(counter); }
}

{ get, set } = Object.getOwnPropertyDescriptor(Element.prototype, "counter");
{ get, set, initialize } = tracked({get, set}, { kind: "field", name: "counter", isStatic: false })
Object.defineProperty(Element.prototype, "counter", {get, set});

Limited access to private fields and methods

Sometimes, certain code outside of a class may need to access private fields and methods. For example, two classes may be "collaborating", or test code in a different file needs to reach inside a class.

Decorators can make this possible by giving someone access to a private field or method. This may be encapsulated in a "private key"--an object which contains these references, to be shared only with who's appropriate.

import { PrivateKey } from "./private-key.mjs"

let key = new PrivateKey;

export class Box {
  @key.show #contents;
}

export function setBox(box, contents) {
  return key.set(box, contents);
}

export function getBox(box) {
  return key.get(box);
}

Note that this is a bit of a hack, and could be done better with constructs like references to private names with private.name and broader scope of private names with private/with. But it shows that this decorator proposal "naturally" exposes existing things in a useful way.

// private-key.mjs
export class PrivateKey {
  #get;
  #set;
  
  show({get, set}) {
    assert(this.#get === undefined && this.#set === undefined);
    this.#get = get;
    this.#set = set;
    return {get, set};
  }
  get(obj) {
    return this.#get(obj);
  }
  set(obj, value) {
    return this.#set(obj, value);
  }
}

This example could be roughly desugared as follows:

let initialize, get, set;
export class Box {
  #_contents = initialize(undefined);
  get #contents() { return get.call(this); }
  set #contents(v) { set.call(this, v); }

  static #_ = (
    get = function() { return this.#_contents; },
    set = function(v) { this.#_contents = v; }
  )
}
{get, set, initialize} = key.show({get, set}, {kind: "field", isStatic: false});

@deprecated

The @deprecated decorator prints warnings when a deprecated field, method or accessor is used. As an example usage:

import { deprecated } from "./deprecated.mjs"

export class MyClass {
  @deprecated field;

  @deprecated method() { }

  otherMethod() { }
}

To allow the deprecated to work on different kinds of class elements, the kind field of the context object lets decorators see which kind of syntactic construct they are deprecating. This technique also allows an error to be thrown when the decorator is used in a context where it can't apply--for example, the entire class cannot be marked as deprecated, since there is no way to intercept its access.

// deprecated.mjs

function wrapDeprecated(fn) {
  let name = fn.name
  function method(...args) {
    console.warn(`call to deprecated code ${name}`);
    return fn.call(this, ...args);
  }
  method.name = name;
  return method;
}

export function deprecated(element, {kind}) {
  switch (kind) {
    case 'method':
    case 'getter':
    case 'setter':
      return wrapDecorated(element);
    case 'field': {
      let { get, set } = element;
      return { get: wrapDeprecated(get), set: wrapDeprecated(set) };
    }
    default: // includes 'class'
      throw new Error(`Unsupported @deprecated target ${kind}`);
  }
}

The desugaring here is analogous to the above examples, which show the use of kind.

Method decorators requiring initialization work

Some method decorators are based on executing code when the class instance is being created. For example:

  • A @on('event') decorator for methods on classes extending HTMLElement which registers that method as an event listener in the constructor.
  • A @bound decorator, which does the equivalent of this.method = this.method.bind(this) in the constructor. This idiom meets Jordan Harband's goal of being friendlier to monkey-patching than the popular idiom of using an arrow function in a field initializer.

Pattern A: Mixin constructors accessing metadata

These decorators can be built with the combination of metadata, and a mixin which performs the initialization actions in its constructor.

@on with a mixin

class MyElement extends WithActions(HTMLElement) {
  @on('click') clickHandler() { }
}

This decorator could be defined as follows:

const handler = Symbol("handler");
function on(eventName)
  return (method, {name}) => {
    context.metadata = {[handlers]: eventName};
    return method;
  }
}

let handlersMap = new WeakMap();  // new.target -> [{method, eventname}]
function getHandlers(newTarget, mixinClass) {
  let handlers = handlersMap.get(newTarget);
  if (handlers === undefined) {
    handlers = [];
    while (newTarget !== null && klass !== mixinClass) {
      for (const [name, {[handlers]: eventName}]
           of Object.entries(klass[Symbol.metadata].instance.methods)) {
        if (eventName !== undefined) {
          handlers.push({method: klass.prototype[name], eventName});
        }
      }
      klass = klass.__proto__;
    }
    handlersMap.set(newTarget, handlers)
  }
  return handlers;
}

function WithActions(superclass) {
  return class C extends superclass {
    constructor(...args) {
      super(...args);
      let handlers = getHandlers(new.target, C);
      for (const {method, eventName} of handlers) {
        this.addEventListener(eventName, method);
      }
    }
  }
}

@bound with a mixin

@bound could be used with a mixin superclass as follows:

class C extends WithBoundMethod(Object) {
  #x = 1;
  @bound method() { return this.#x; }
}

let c = new C;
let m = c.method;
m();  // 1, not TypeError

This decorator could be defined as:

const boundName = Symbol("boundName");
function bound(method, context) {
  context.metadata = {[boundName]: true};
  return method;
}

let boundNameMap = new WeakMap();  // new.target -> [names]
function getBoundNames(newTarget, mixinClass) {
  let names = boundNameMap.get(newTarget);
  if (names === undefined) {
    names = [];
    while (newTarget !== null && klass !== mixinClass) {
      for (const [name, annotations] of
           Object.entries(klass[Symbol.metadata].instance.methods)) {
        if (annotations[boundName]) {
          handlers.push(name);
        }
      }
      klass = klass.__proto__;
    }
    boundNameMap.set(newTarget, names)
  }
  return names;
}

function WithBoundMethods(superclass) {
  return class C extends superclass {
    constructor(...args) {
      super(...args);
      let names = getBoundNames(new.target, C);
      for (const name of names) {
        this[name] = this[name].bind(this);
      }
    }
  }
}

Pattern B: The init contextual keyword for methods

If it's not acceptable to require a superclass/mixin for cases requiring initialization action, an The init keyword in a method declaration changes a method into an "init method". This keyword allows decorators to add initialization actions, run when the constructor executes.

@on with init

Usage:

class MyElement extends HTMLElement {
  @on('click') init clickHandler() { }
}

An "init method" (method declared with init) is called similarly to a method decorator, but it is expected to return a pair {method, initialize}, where initialize is called with the this value being the new instance, taking no arguments and returning nothing.

function on(eventName) {
  return (method, context) => {
    assert(context.kind === "init-method");
    return {method, initialize() { this.addEventListener(eventName, method); }};
  }
}

The class definition would be desugared roughly as follows:

let initialize;
class MyElement extends HTMLElement {
  clickHandler() { }
  constructor(...args) {
    super(...args);
    initialize.call(this);
  }
}
{method: MyElement.prototype.clickHandler, initialize} =
  on('click')(MyElement.prototype.clickHandler,
              {kind: "init-method", isStatic: false, name: "clickHandler"});

@bound with init

The init keyword for methods can also be used to build a @bound decorator, used as follows:

class C {
  #x = 1;
  @bound init method() { return this.#x; }
}

let c = new C;
let m = c.method;
m();  // 1, not TypeError

The @bound decorator can be implemented as follows:

function bound(method, {kind, name}) {
  assert(kind === "init-method");
  return {method, initialize() { this[name] = this[name].bind(this); }};
}

Syntax

This decorators proposal uses the syntax of the previous Stage 2 decorators proposal. This means that:

  • Decorator expressions are restricted to a chain of variables, property access with . but not [], and calls (). To use an arbitrary expression as a decorator, @(expression) is an escape hatch.
  • Class expressions may be decorated, not just class declarations`.
  • Class decorators come after export and default.

There is no special syntax for defining decorators; any function can be applied as a decorator.

Detailed semantics

The three steps of decorator evaluation:

  1. Decorator expressions and s (the thing after the @) are evaluated interspersed with computed property names.
  2. Decorators are called (as functions) during class definition, after the methods have been evaluated but before the constructor and prototype have been put together.
  3. Decorators are applied (mutating the constructor and prototype) all at once, after all of them have been called.

The semantics here generally follow the consensus at the May 2016 TC39 meeting in Munich.

1. Evaluating decorators

Decorators are evaluated as expressions, interspersed in their evaluation order with computed property names. This goes left to right, top to bottom. The result of decorators is stored in the equivalent of local variables to be later called after the class definition initially finishes executing.

2. Calling decorators

The element being wrapped: the first parameter

The first parameter, of what the decorator is wrapping, depends on what is being decorated:

  • In a method, init-method, getter or setter decorator: the relevant function object
  • In a class decorator: the class
  • In a field: An object with two properties
    • get: A function which takes no arguments, expected to be called with a receiver which is the appropriate object, returning the underlying value.
    • set: A function which takes a single argument (the new value), expected to be called with a receiver which is the object being set, expected to return undefined.

The context object: the second parameter

The context object--the object passed as the second argument to the decorator--contains the following properties:

  • kind: One of
    • "class"
    • "method"
    • "init-method"
    • "getter"
    • "setter"
    • `"field"``
  • name:
    • Public field or method: the name is the String or Symbol property key.
    • Private field or method: missing (could be provided as some representation of the private name, in a follow-on proposal)
    • Class: missing
  • isStatic:
    • Static field or method: true
    • Instance field or method: false
    • Class: missing

The "target" (constructor or prototype) is not passed to field or method decorators, as it has not yet been built when the decorator runs.

The return value

The return value is interpreted based on the type of decorator. The return value is expected as follows:

  • Class: A new class
  • Method, getter or setter: A new function
  • field: An object with three properties (each individually optional):
    • get: A function of the same form as the get property of the first argument
    • set: Ditto, for set
    • initialize: A called with the same arguments as set, which returns a value which is used for the initializing set of the variable. This is called when initially setting the underlying storage based on the field initializer or method definition. This method shouldn't call the set input, as that would trigger an error. If initialize isn't provided, set is not called, and the underlying storage is written directly. This way, set can count on the field already existing, and doesn't need to separately track that.
  • Init method: An object with the properties
    • method: A function to replace the method
    • initialize: A function with no arguments, whose return value is ignored, which is called with the newly constructed object as the receiver.

3. Applying decorators

Decorators are applied after all decorators have been called. The intermediate steps of the decorator application algorithm are not observable--the newly constructed class is not made available until after all method and non-static field decorators have been applied.

The class decorator is called only after all method and field decorators are called and applied.

Finally, static fields are executed and applied.

Decorated field semantics in depth

Decorated fields have the semantics of getter-setter pairs backed by a private field. That is,

function id(v) { return v; }

class C {
  @id x = y;
}

has the semantics of

class C {
  #x = y;
  get x() { return this.#x; }
  set x(v) { this.#x = v; }
}

These semantics imply that decorated fields have "TDZ" like private fields. For example, the following is a TypeError because y is accessed before it is added to the instance.

class C {
  @id x = this.y;
  @id y;
}
new C;  // TypeError

The getter/setter pair are ordinary JS method objects, and non-enumerable like other methods. The underlying private fields are added one-by-one, interspersed with initializers, just like ordinary private fields.

Possible extensions

This decorators proposal was designed to permit other syntactic elements to be decorated:

Annotation syntax

Annotations, a declarative complement to decorators, use the syntax @{ }, which behaves exactly like an object literal. Arbitrary expressions, spread, computed property names, etc, are permitted. It is accessible from the annotated object through the [Symbol.metadata] property.

@{x: "y"} @{v: "w"} class C {
  @{a: "b"} method() { }
  @{c: "d"} field;
}

C[Symbol.metadata].class.x                     // "y"
C[Symbol.metadata].class.v                     // "w"
C[Symbol.metadata].prototype.methods.method.a  // "a"
C[Symbol.metadata].instance.fields.field.c     // "d"

Annotations must always have a literal @{ to start them. To use an existing object as an annotation, you can use the syntax @{ ...obj }. The entirity of object syntax is available, including computed property names, arbitrary expressions as values, shorthand names, concise methods, etc.

Libraries and frameworks which want to establish consistent conventions for using annotations may do so based on a Symbol property key that they export. Annotations have the potential advantage in load time performance that engines can directly execute them, as they are as declarative as an object literal.

Annotation semantics may be useful for cases like ORMs and serialization frameworks, which need information about class fields, without affecting their normal runtime semantics. However, the popular ecosystem examples that we've found of this form, using just metadata for fields, seem to depend on metadata generated by TypeScript types. From these examples, it seems that annotation syntax alone would not be a sufficient solution.

Some frameworks, including Angular, tend to use decorators which operate primarily by adding metadata. However, object literal annotations are not quite suitable for this usage, as they don't provide a way to be annotated in TypeScript to check types the way that functions do, they don't allow any processing of the metadata in code before it is saved, and because they don't provide a usable, stable identifier to be used for custom static analysis tools like tree shaking. For Angular, it may make more sense to use decorators which add metadata.

For these reasons, annotations are omitted from this proposal's "MVP" (minimum viable product) and considered as a possible follow-on proposal.

Function decorators and annotations

The @logged decorator from earlier would Just Work(TM) on a function, with function decorators!

@logged
@{x: "y"}
function f() { }

f();                        // prints logging information
f[Symbol.annotations][0].x  // "y"

Function declarations with decorators or annotations are not hoisted. This is because it would be unintuitive to reorder the evaluation of the decorator or annotation expressions.

Instead, functions with decorators or annotations are defined only when their declaration is reached. If they are used before they are defined, a ReferenceError is thrown, like classes. This ReferenceError condition is sometimes referred to as a "temporal dead zone" (TDZ). The TDZ risks unfortunate situations when refactoring, but at least those situations lead to easy-to-debug errors rather than the wrong function being run.

Function decorator details:

  • First parameter: the function being decorated (or, whatever the next inner decorator returned)
  • Second parameter: a context object which just has { kind: 'function' }
  • Return value: a new function, or undefined to keep the same function

The inner binding of a function expression inside itself is in TDZ until all the function decorators run.

Parameter decorators and annotations

A parameter decorator wraps the value of a function/method argument. It returns a function which does the wrapping.

function dec(_, context) {
  assert(context.kind === "parameter");
  return arg => arg - 1;
}

function f(@dec @{x: "y"} arg) { return arg * 2 ; }

f(5)  // 8
f[Symbol.annotations].parameters[0].x  // "y"

Functions with parameters that are decorated or annotated are treated similarly to decorated/annotated functions: they are not hoisted, and are in TDZ until their definition is executed.

Parameter decorator details:

  • First parameter: undefined
  • Second parameter: a context object which just has { kind: 'parameter' }
  • Return value: a function which takes a parameter value and returns a new parameter value. The function is called with the this value that the surrounding function is called with.

This example can be desugared as

let decInstance = dec(undefined, {kind: "parameter"});

function f(arg_) {
  const arg = decInstance(arg_);
  return arg * 2 ;
}

f[Symbol.annotations] = []
f[Symbol.annotations].parameters = []
f[Symbol.annotations].parameters[0] = {x: "y"};

let decorators

Variables declared with let can be decorated, converting them into special getter/setter pairs that are invoked when the variable is read or written.

let @deprecated x = 1;
++x;  // Shows deprecation warnings for read and write

let decorators might be useful for systems using reactivity based on local variables, e.g. "hooks" systems.

let decorator details:

  • First parameter: A { get, set, value } object (where the receiver is expected to be undefined, and where value is the RHS)
  • Second parameter: a context object { kind: "let" }
  • Return value: A { get, set, value } object, with potentially new behavior

This example can be desugared as:

let { get_x, set_x, value: _x } = depreciated({value: 1, get() { return _x; }, set(v) { _x = v; }}, {kind: "let"});

set_x(get_x()++);

const decorators

Variables declared with const can be decorated more simply--the decorator simply wraps the value being decorated when it's being defined.

function inc(x) { return x+1; }
const @inc x = 1;  // 2

const decorator details:

  • First parameter: The value of the RHS
  • Second parameter: a context object { kind: "const" }
  • Return value: A new value for the variable

This could be desugared as follows:

const x = inc(1, {kind: "const"});

(This form isn't so useful by itself, but may become more important if future proposals share more information through the context object.)

Object literal and property decorators and annotations

  • A decorated object literal works like a class decorator, but with kind: "object".
  • A decorated method, getter or setter in an object literal works just like one in a class, replacing that method.
  • A decorated object property works like a field decorator, but with kind: "property", and it receives the initial value in the value property of the input, and returns it in the output object, rather than returning an initializer function, since it only runs once (in this way, it is similar to let decorators).

Example:

const x = @decA {
  @decB p: v,
  @decC m() { }
};

Motivation

Design goals

It should be easy both to use decorators and to write your own decorators.

Decorators should affect the thing they're decorating, and avoid confusing/non-local effects.

Use case analysis

Some essential use cases that we've found include:

  • Storing metadata about classes, fields and methods
  • Turning a field into an accessor
  • Wrapping a method

(TODO: Fill this in with more detail)

Transpiler and native implementation constraints

From transpilers:

  1. The transpiler output shouldn't be too big (both in terms of the direct output of the translation, and the size of the support library)
  2. It should be possible to transpile on a file-by-file basis, without cross-file information

From native implementations: A: The "shape" of the class should be apparent syntactically, without executing code B: It should not be too complicated to process decorators, as this corresponds to a complex implementation C: Minimize or eliminate observable mutations to objects while setting up the class

Constraints 2 + A together imply that all shape changes must be syntactically apparent. This constraint is met by making all shape changes syntactically aparent where the class is defined, by making it explicit to either opt into an "annotation" instead of the default (or, in a previous proposal with the opposite default, a "trap").

Out of scope

Some things that have been described as potential decorators would not fit into the scheme here, and would require either dedicated syntax to meet the constraints raised by TC39 delegates, or the use of existing idioms to work around the need for a decorator.

  • @set: This decorator would change a field from [[Define]] semantics to [[Set]]. This decorator changes which kind of code executes in the constructor in a different way which is not visible from syntax. These semantics can be accessed by putting a line of code in the constructor rather than a field declaration. However, note that this proposal reduces the need for opting into [[Set]] semantics in multiple ways:
    • [[Set]] semantics drove how fields worked with legacy/experimental decorators which created accessors. These mechanics are replaced in this proposal by having decorated field declarations initialize the underlying storage, not shadow the accessor.
    • If a setter is inherited, it is possible to write a decorator for a field which specifically calls super getters and setters, rather than using the underlying storage.
  • @frozen: This decorator freezes the whole class, including static fields. Such a change is not possible within the phase ordering of decorators, where class decorators run before static fields are executed. Instead, the class can be frozen in a single line after the class, or potential future syntax for freezing the class.
  • @enumerable: This decorator would make a method enumerable, overriding its default of non-enumerable. Decorators cannot change property attributes, as they do not receive property descriptors to manipulate them as in Stage 1 decorators, and they are not passed the constructor of the class to do so imperatively. This is to meet requirements from implementations that decorators leave classes with statically predictable shapes. Instead, changes like this could be done by Object.defineProperty calls after the class definition executes.
  • @reader: This decorator for a private field would create a public accessor to read it. It is impossible to create, as decorators are not given access to the class. Such a change in shape would run counter to the "static shape" goals from native implementers.

Relationship to earlier proposals

(TODO)

Standardization plan

  • Present in September 2020, or whenever it is ready
  • Iterate on open questions within the proposal, presenting them to TC39 and discussing further in the biweekly decorators calls, to bring a conclusion to committee in a future meeting:
    • Should annotation syntax be included in the MVP, or added in a follow-on proposal? (Annotations added by decorators seem necessary for the MVP either way.)
    • What should the details of the annotation object model be? (This definitely needs iteration.)
    • How should init method use cases be handled--the contextual keyword, mixins+annotations, or some other model? How important are these use cases for the MVP?
  • If feedback is positive, write spec text and implement in transpilers
  • Propose for Stage 3 no sooner than six months after prototyping begins, so we have time to collect experience from developers in transpilers
@ljharb
Copy link

ljharb commented Aug 11, 2020

the gist has been updated to address this concern I'm very confused about `@bound`. The semantics I want for `class C { @bound foo() {} }` are that `C.prototype.foo` is a data property containing a function, like any other class method, and that this is effectively sugar for `class C { foo = this.foo.bind(this); foo() {} }`. I very much do not want any getter/setter magic, I want the simple pattern that this decorator typically is used for. Encouraging arrow functions in fields is an antipattern, and testability requires a prototype method that can be spied upon prior to construction.

@mweststrate
Copy link

Missed the meeting as I was on holiday, but love the proposal! From top of my head I think it addresses all concerns / use cases I have :)

@shicks
Copy link

shicks commented Sep 1, 2020

@littledan, I would like to see @final—as applied both to entire classes (to prevent another class extending it) and to individual methods (to prevent a subclass overriding it)—explicitly called out as either a concrete example or else explicitly added to the list of "out of scope" use cases.

(For context, as the maintainer of a large common library in a giant monorepo, we have found Closure Compiler's enforcement of /** @final */ to be immensely useful in preventing (both intended and unintended) misuse of our APIs. Anecdotally, cases where the annotation was omitted have caused us significant pain because downstream subclasses have prevented much-needed cleanups (and in a monorepo, this is a hard blocker). As we move to TypeScript, we are sorely missing this enforcement, and TS will not implement it if it doesn't come from TC39.)

@littledan
Copy link
Author

@shicks While I can see how this would be useful, it's not clear to me how it would fit into JS runtime semantics. It sounds more like something to enforce at build time. Maybe this is better to keep a feature of type systems and linters? I'd like to understand TS's position here better, as I don't really see what we could do in the language.

@shicks
Copy link

shicks commented Sep 6, 2020

@littledan I can imagine a way to enforce it at runtime (i.e. in userland via decorators) but it's pretty expensive. Basically, replace the constructor with a version that makes sure new.target === myself (for final classes), or for final methods, iterates over the final methods at instantiation time to ensure they're the version from myself.prototype. It's not great, but theoretically doable.

That said, I completely agree with you that build time is the appropriate time to check this. The TypeScript team's arguments against it seem to be that (1) classes are a JS feature, not a TS feature, so it's TC39's job to implement this if it's actually important, since they don't want to deviate from the spec (a la enum/namespace), (2) it's nonsense to be able to new something but not subclass it since it's basically the same thing, (3) they don't want a keyword soup, (4) you can check it at runtime, so why bother checking at build time?, (5) you can write a lint check for specific classes you really care about, (6) nobody's going to accidentally subclass something, (7) you can't guarantee security. See microsoft/TypeScript#8306 (comment) for the full discussion. I honestly don't see any of those arguments as holding much water, but it's a very heated debate and one that the TS team (and @RyanCavanaugh in particular) seems to be tired of and refuses to reconsider.

In any case if TypeScript refuses to implement it (which seems the most likely) then our only recourse will be to implement our own custom decorator and add some sort of extra check to our wrapped tsc. If decorators end up in EcmaScript, it would be ideal if @final wasn't just our own custom decorator, but was a well-known standard (which could be enforced in uncompiled mode, but we'd likely strip from optimized code), hence why I'm asking here (to make a short story long).

EDIT: Also, FWIW, if it were a standard decorator, it's possible that TypeScript would be motivated to actually enforce it directly, rather than requiring custom wrappers - at least it wouldn't be adding any keywords.

@littledan
Copy link
Author

I'd hope that a @final decorator could trigger an error when subclassing, not when using it. I don't think this decorators proposal is a good fit for those semantics. I have to say, though, I find some of TS's arguments pretty convincing.

@shicks
Copy link

shicks commented Sep 6, 2020

I agree that it would be much better at class definition time, but see no feasible way to do it in userland. Which is kind of my point - if TS passes the buck to TC39 and TC39 passes the buck to "build", then it's a non-starter and we're not going to have any better.

@littledan
Copy link
Author

Maybe you could make some other kind of checker in your pipeline, apart from TS, if this is important for you but not TS upstream?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment