Home > other >  How do I use symbols as keys
How do I use symbols as keys

Time:11-03

I want to do this

interface test {
  [k: symbol]: (e: string) => void;
}
const S = Symbol()

const obj: test = { [S]: (data) => { console.log(data)  } }

Parameter 'data' implicitly has an 'any' type.(7006)

I expected "data" to be a string,What did I get wrong?

CodePudding user response:

I work around and see that:

const S = Symbol() // S will be "typeof S" not a symbol

If you change S to

const S: symbol = Symbol() // S will be a symbol
// OR
let S = Symbol() // S will be a symbol

, your code will works.

I think Typescript team already implement it to solve issues. I'm waiting for some explaination.

Playground

  • Related