Ognjen Mišić
Ognjen Mišić

Reputation: 1416

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.

Upvotes: 1

Views: 465

Answers (2)

Phani
Phani

Reputation: 88

You can use 'keyof' of operator for that.

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

Upvotes: 0

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

Playground

Upvotes: 2

Related Questions