TypeScript | Known and Unknown Keys

(Last edited: October 29, 2019)

interface IMyColor {
  hex: string
  rgb: string
  [key: string]: any
}

const iColor: IMyColor = {
  hex: '#bada55',
  rgb: 'rgb(1, 2, 3)',
  unknownColor: 42, // valid
}

const whatColorInterface = iColor.whatIsThis // any

type MyColorType = {
  [key: string]: any
} & {
  hex: string
  rgb: string
}

const colorType: MyColorType = {
  hex: '#bada55',
  rgb: 'rgb(1, 2, 3)',
  unknownColor: 42, // valid
}

const whatColorType = colorType['is this a valid key'] // any

There are cases where we have known and unknown keys in an object. Having at least the known keys will help with TypeScript code assistance. But, it’s generally better to avoid these kinds of types because it’s harder to guarantee type safety.

Playground example.


© 2022, built with Gatsby. Subscribe via RSS.
Crafted by John Darryl Pelingo
. All rights reserved.