首页 > 解决方案 > 如何使用对象条目作为打字稿中嵌套对象的索引?

问题描述

我正在尝试使用对象条目作为嵌套对象的索引,如下所示:

type Size = 'small' | 'medium' | 'large';
type Variant = 'primary' | 'secondary';

const styles: {
  size: Record<Size, object>;
  variant: Record<Variant, object>;
} = {
  size: {
    small: { padding: 8 },
    medium: { padding: 12 },
    large: { padding: 16 },
  },
  variant: {
    primary: { background: 'hotpink' },
    secondary: { background: 'silver' },
  },
};

const props: { size: Size; variant: Variant } = {
  size: 'medium',
  variant: 'primary',
};

const css = (Object.keys(props) as Array<keyof typeof props>).reduce(
  (acc, key) => {
    const value = props[key];
    return { ...acc, ...styles[key][value] };
    //                  ^ Element implicitly has an 'any' type because
    // expression of type '"small" | "medium" | "large" | "primary" | "secondary"'
    // can't be used to index type 'Record<Size, object> | Record<Variant, object>'
  },
  {}
);

as Array<keyof typeof ...>用来避免Object.keys只提供string[]密钥——但我不确定如何处理生成的联合类型?

标签: typescript

解决方案


推荐阅读