Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

TypeScript Symbols


May 07, 2021 TypeScript


Table of contents


Introduction to TypeScript Symbols

Since ECMAScript 2015, symbol become a new native type, just number string string.

symbol of the symbol type Symbol by the Symbol constructor.

let sym1 = Symbol();

let sym2 = Symbol("key"); // 可选的字符串key

Symbols is imm changed and unique.

let sym2 = Symbol("key");
let sym3 = Symbol("key");

sym2 === sym3; // false, symbols是唯一的

Like strings, symbols can also be used as keys for object properties.

let sym = Symbol();

let obj = {
    [sym]: "value"
};

console.log(obj[sym]); // "value"

Symbols can also be combined with calculated property name declarations to declare properties and class members of an object.

const getClassNameSymbol = Symbol();

class C {
    [getClassNameSymbol](){
       return "C";
    }
}

let c = new C();
let className = c[getClassNameSymbol](); // "C"

It is well known as Symbols

In addition to user-defined symbols, there are already well-known built-in symbols. Built-in symbols are used to represent behavior within the language.

Here's a list of these symbols:

Symbol.hasInstance

method, which is instanceof the instanceof operator. Constructor objects are used to identify whether an object is an instance of it.

Symbol.isConcatSpreadable

Boolean value, which indicates whether an array element of an object can be expanded when Array.prototype.concat is called on an object.

Symbol.iterator

Method, for-of statement. Returns the object's default iterator.

Symbol.match

Method, String.prototype.match Regular expressions are used to match strings.

Symbol.replace

Method, String.prototype.replace Regular expressions are used to replace matching substrings in strings.

Symbol.search

Method, String.prototype.search The regular expression returns the index of the matched part in the string.

Symbol.species

The function value, which is a constructor. Used to create derived objects.

Symbol.split

Method, String.prototype.split Regular expressions are used to split strings.

Symbol.toPrimitive

Method, ToPrimitive abstract operation. Convert the object to the appropriate original value.

Symbol.toStringTag

Method, called by the Object.prototype.toString Returns the default string description when the object was created.

Symbol.unscopables

Object, its own properties are with by the with scope.