有关打字稿符号作为对象属性标识符的问题

时间:2019-11-05 00:35:16

标签: typescript object key symbols

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

像这样的代码片段:


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));

得到结果:

[
  "name",
  "age"
]

问题是sym不是对象键。为什么?

1 个答案:

答案 0 :(得分:1)

这就是Object.keys的工作方式。它不返回符号。如果需要符号,请使用Object.getOwnPropertySymbols

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]]);