Constant-named properties

TypeScript 2.7 adds support for declaring const-named properties on types including ECMAScript symbols.

Example

  1. // Lib
  2. export const SERIALIZE = Symbol("serialize-method-key");
  3. export interface Serializable {
  4. [SERIALIZE](obj: {}): string;
  5. }
  1. // consumer
  2. import { SERIALIZE, Serializable } from "lib";
  3. class JSONSerializableItem implements Serializable {
  4. [SERIALIZE](obj: {}) {
  5. return JSON.stringify(obj);
  6. }
  7. }

This also applies to numeric and string literals.

Example

  1. const Foo = "Foo";
  2. const Bar = "Bar";
  3. let x = {
  4. [Foo]: 100,
  5. [Bar]: "hello",
  6. };
  7. let a = x[Foo]; // has type 'number'
  8. let b = x[Bar]; // has type 'string'

unique symbol

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.

Example

  1. // Works
  2. declare const Foo: unique symbol;
  3. // Error! 'Bar' isn't a constant.
  4. let Bar: unique symbol = Symbol();
  5. // Works - refers to a unique symbol, but its identity is tied to 'Foo'.
  6. let Baz: typeof Foo = Foo;
  7. // Also works.
  8. class C {
  9. static readonly StaticSymbol: unique symbol = Symbol();
  10. }

Because each unique symbol has a completely separate identity, no two unique symbol types are assignable or comparable to each other.

Example

  1. const Foo = Symbol();
  2. const Bar = Symbol();
  3. // Error: can't compare two unique symbols.
  4. if (Foo === Bar) {
  5. // ...
  6. }