繁体   English   中英

对象属性值作为类型

[英]Object property value as type

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

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

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

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

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

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

操场

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM