对象属性值作为类型

时间:2021-07-20 07:42:47

标签: reactjs typescript

如果我有一个对象,例如:

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

我如何告诉打字稿“我想允许传递任何颜色的对象属性”,例如,如果我正在制作一个图标组件:

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

请注意,我不想说 fill 可以是 fill: Colors.blueish | Colors.grayish,因为我希望将来可以将任何颜色添加到我的 Colors 对象中。

2 个答案:

答案 0 :(得分:2)

您需要使 Colors 对象不可变,否则 TS 会将颜色值推断为 string 而不是 "#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

答案 1 :(得分:0)

您可以为此使用运算符的“keyof”。

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