Alexander Mills
Alexander Mills

Reputation: 100250

Define symbol as property using lazy initialization

I have this:

export const symbols = {
  toString: Symbol('@xml.js.toString')
};

export class Node {

  [key: string]: any;

  [symbols.toString] = function(){

  };

}

but I get this error:

enter image description here

Which is:

A computed property name in class property declaration must refer to an expression whose type is a literal type or unique symbol type.

Anyone know what's going on?

If I put it in the constructor, I don't get an error:

enter image description here

Upvotes: 2

Views: 634

Answers (1)

Estus Flask
Estus Flask

Reputation: 222935

As the error states, only unique symbols can be used as computed property names.

As described in the reference,

To enable treating symbols as unique literals a new type unique symbol is available. unique symbol is are subtype of symbol, and are produced only from calling Symbol() or Symbol.for(), or from explicit type annotations. The new type is only allowed on const declarations and readonly static properties, and in order to reference a specific unique symbol, you’ll have to use the typeof operator. Each reference to a unique symbol implies a completely unique identity that’s tied to a given declaration.

Due to listed limitations, object property cannot be unique.

Instead, it can be:

export namespace symbols {
  export const toString = Symbol('@xml.js.toString');
};

Upvotes: 3

Related Questions