简体   繁体   中英

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:

在此处输入图片说明

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:

在此处输入图片说明

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');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM