missannil
missannil

Reputation: 137

How do I use symbols as keys

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?

Upvotes: 1

Views: 194

Answers (1)

Long Nguyen Duc
Long Nguyen Duc

Reputation: 1325

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

Upvotes: 1

Related Questions