When defining a Typescript interface with computed keys, I encountered some design challenges:
const NAMESPACE = 'com.pizza'
const KEY_SAUCE = `${NAMESPACE}/sauce`
const KEY_CRUST = `${NAMESPACE}/crust`
interface PizzaToken {
radius: number
[KEY_SAUCE]: Sauce
[KEY_CRUST]: Crust
}
const pizza: PizzaToken = PizzaFactory.getToken(...)
console.log(pizza[KEY_SAUCE])
This approach led to two unrelated Typescript errors. The first error pertains to the interface:
TS1169: A computed property name in an interface must refer to an
expression whose type is a literal type or a 'unique symbol' type.
The second error occurred when accessing pizza[KEY_SAUCE]
:
TS7053: Element implicitly has an 'any' type because expression of
type 'any' can't be used to index type 'Pizza'.
While workarounds like using Symbol
can solve these issues, they are not ideal. What would be the most effective method to overcome these obstacles?