typescript 具有列表中变量键的嵌套对象的类型

uttx8gqw  于 2023-01-10  发布在  TypeScript
关注(0)|答案(1)|浏览(153)

我有以下两个对象,它们定义了Button的变量样式。

interface colorProps {
  cyan: string;
  white: string;
  gray: string;
}

interface variantProps {
  solid: string;
  outline: string;
}

type styleProps = {  // unused
  [Key in keyof variantProps]: {[key in keyof colorProps]: string} | colorProps | string | keyof colorProps;
}

interface CustomProps {
  [key: string]: string | {[key: string]: string} | keyof colorProps | colorProps | variantProps | keyof variantProps;
}

const baseStyles: CustomProps = {
  solid: 'xxx',
  outline: 'xxx',
}

const variantStyles: CustomProps = {
  solid: {
    cyan: 'xxx',
    white: 'xxx',
    gray: 'xxx',
  },
  outline: {
    gray: 'xxx',
  },
}

我定义了按钮的输入属性类型,如下所示:

interface ButtonProps {
    href?: string;
    variant?: keyof variantProps;//'solid' | 'outline';
    color?: keyof colorProps;//'cyan' | 'white' | 'gray';
    className?: string;
}

我正在尝试做一些我可以很容易地在其他类型语言,即只是:

variantStyles[variant][color]

所以我试图根据variantcolor的值得到正确的样式。正如你所看到的,我在CustomProps中尝试了很多东西(除了输入any),但仍然得到:

Element implicitly has an 'any' type because expression of type 'keyof colorProps' can't be used to index type 'string | colorProps | { [key: string]: string; } | variantProps'.
  Property 'cyan' does not exist on type 'string | colorProps | { [key: string]: string; } | variantProps'.ts(7053)
e5nqia27

e5nqia271#

将CustomProps界面更改为:

interface CustomProps {
    [key: string]: {
        [key: string]: string | keyof colorProps | colorProps | variantProps | keyof variantProps;
    };
}

相关问题