자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Typescript] 21장 심볼

728x90

✅ 1. Symbol의 기본 개념

Symbol(심볼)은 절대 중독되지 않는 유일한 값을 생성하고 같은 설명(description)을 줘도 값은 다릅니다. 객체의 키(Key)로 많이 쓰이고 있습니다.

const a = Symbol('id');
const b = Symbol('id');

console.log(a === b); // false;

✅ 2.Symbol 생성 방법

const mySymbol = Symbol(); // Creating a symbol without a description
const mySymbol2 = Symbol('description'); // Creating symbols

console.log(mySymbol2.toString()); // Symbol(description)

✅ 3. Symbol을 객체 키로 사용

const id = Symbol('id'); // Creating a unique symbol with a description

const user = {
  name: 'Alice',
  [id]: 12345, // Using the Symbol as a key
};

console.log(user.name); // Alice
console.log(user[id]); // 12345 );
  • for...in 반복문이나 Object.keys()로는 Symbol 키가 안나옴
  • Object.getOwnPropertySymbols()를 사용해야 조회 가능
console.log(Object.keys(user)); // ["name"]);
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id) ]

4. 전역 Symbol (Symbol.for / Symbol.keyFor)

  • Symbol.for(key) -> 같은 키가 있으면 기존 Symbol 재사용
  • Symbol.keyFor(Symbol) -> 전역 Symbol의 키를 가져옴
let s1 = Symbol.for('shared');
let s2 = Symbol.for('shared');

console.log(s1 === s2); // true

console.log(Symbol.keyFor(s1)); // "shared");

5. 내장 심볼 예시

// 1) Symbol.iterator : for...of loop
const myArray = [1, 2, 3];
const iterator = myArray[Symbol.iterator]();

console.log(iterator.next()); // { value: 1, done: false }

// 2) Symbol.toStringTag : custom object string representation
const myObject = {
  [Symbol.toPrimitive](hint: string) {
    if (hint === 'number') return 42;
    return 'Object';
  },
};

console.log(+myObject); // 42
console.log(`${myObject}`); // "Object"

 

 

GitHub - Koras02/typescript-bloging

Contribute to Koras02/typescript-bloging development by creating an account on GitHub.

github.com

 

728x90
LIST