0

Given a symbol

const title = Symbol('Csv column title');

representing a key of an object and the text of a header in a table. I thought I could setup the headers like so

const tableHeaders: { key: string }[] = [{ key: title }];

but unfortunately I get the errors

Type 'symbol' is not assignable to type 'string'.(2322)

and

TypeError: Cannot convert a Symbol value to a string

It seems Symbol.prototype.toString() is not what I'm looking for since Symbol('title').toString() returns "Symbol(title)".

How can I use the symbol as a string?

baitendbidz
  • 187
  • 3
  • 19

2 Answers2

0

You may be able to utilise the global symbol registry ¹ ² to achieve this:

const title = Symbol.for('Csv column title');

const tableHeaders: { key: string }[] = [{ key: Symbol.keyFor(title)! }];

If you need to retrive the symbol again you can use Symbol.for(tableHeaders[0].key) which should get the same symbol from the registry.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
-1

You can use keyof and typeof like so :

const title = Symbol('Csv column title');

const tableHeaders: { [key in keyof typeof title]: string }[] = [{ [title]: 'Title' }];
Johan
  • 2,088
  • 2
  • 9
  • 37
  • Thanks for your reply. This code didn't compile in the TS playground ( v4.9.5 ) and I don't think that this is what I'm looking for. The object should be similiar to `{ key: title }` – baitendbidz Feb 13 '23 at 08:42