Object property value as type

If I have an object, for instance:

const Colors = {
  blueish: "#0070C1",
  grayish: "#d6d6d6"

How do I tell typescript "I want to allow any of the Color's object properties to be passed", for instance if I'm making an Icon component:

const Icon = ({fill}: {fill: Colors (compiler complains here))}) => <svg><path fill={fill}/></svg>

Note, I do not want to say fill can be fill: Colors.blueish | Colors.grayish because I want to allow any color in future added to my Colors object.

Submitted July 20th 2021 by Admin


You need to make Colors object immutable, otherwise TS will infer color value as a string instead "#0070C1" | "#d6d6d6".

import React from 'react' const Colors = { blueish: "#0070C1", grayish: "#d6d6d6"
} as const; // returns union of all values
type Values<T> = T[keyof T] const Icon = <T extends Values<typeof Colors>>({ fill }: { fill: T }) => <svg><path fill={fill} /></svg> const y = <Icon fill="#0070C1" /> // ok
const x = <Icon fill="#0070C2" /> // expected error 


Admin | 5 days ago


You can use 'keyof' of operator for that.

const Icon = ({fill}: {fill: keyof typeof Colors}) => <svg><path fill={fill}/></svg>

Admin | 5 days ago

Relevant Questions