TypeScript

Symbol, 유일한 property key

디리릭 2022. 5. 24. 00:00
728x90

symbol은 유일성을 보장한다. 

//유일성 보장함
const sym1 = Symbol("test");
const sym2 = Symbol("test");
console.log(sym1 == sym2);  //false
console.log(sym1 === sym2); //false

//전역변수처럼 사용할 수 있음
const sym3 = Symbol.for("test1");
const sym4 = Symbol.for("test1");
console.log(sym3== sym4);  //true
console.log(sym3 === sym4); //true

const shop = {
    name:"ruru",
    type:"dessert"
};


const showName =Symbol("show me");
shop[showName] = function(){
    console.log(this.name);
};

shop[showName](); //ruru

//심볼형 property는 출력되지 않음 
for(let key in shop)
{
    console.log(`the shop ${key} is ${shop[key]}`);
}
//the shop name is ruru
//the shop type is dessert


//심볼형 property를 출력하는 방법
Object.getOwnPropertySymbols(shop);
Reflect.ownKeys(shop); //심볼형 포함 모든 keys
728x90

'TypeScript' 카테고리의 다른 글

Typescript 란?  (0) 2022.01.03