Hiln Penn
Hiln Penn

Reputation: 3

A question about typescript symbol as a object property identifier

peng@neo-laptop:~/ts-learnings$ tsc --version
Version 3.6.4

While the code snippet like this:


const sym = Symbol('foo');

let o = {
    name: "Jessie Tom",
    age: 35
};

function extendObject(obj: any, sym: symbol, value: any) {
    obj[sym] = value;
}

extendObject(o, sym, 42);

console.log(Object.keys(o));

Got the result:

[
  "name",
  "age"
]

The problem is sym is not a object key. Why?

Upvotes: 0

Views: 138

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85012

That's just how Object.keys works. It does not return symbols. Use Object.getOwnPropertySymbols if you want symbols.

const sym = Symbol('foo');

let o = {
    name: "Jessie Tom",
    age: 35,
};

function extendObject(obj, sym, value) {
    obj[sym] = value;
}

extendObject(o, sym, 42);

console.log(Object.keys(o));
const symbols = Object.getOwnPropertySymbols(o)
console.log(symbols);
console.log(o[symbols[0]]);

Upvotes: 2

Related Questions