Can I define a Typescript interface with computed keys?

Viewed 94

I want to define a Typescript interface with computed keys:

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 design pattern gives me two unrelated Typescript errors; the first, on 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.

and the second on the pizza[KEY_SAUCE]:

TS7053: Element implicitly has an 'any' type because expression of 
type 'any' can't be used to index type 'Pizza'.

I can resolve these with some workarounds (e.g Symbol) but they're kind of clunky. What's the best way to make something like this work?

1 Answers

You need to use as const to make a nonwidening string literal type at the key declarations:

const KEY_SAUCE = `${NAMESPACE}/sauce` as const;
const KEY_CRUST = `${NAMESPACE}/crust` as const;
Related