打字稿:定义“需要键之一”的嵌套对象的接口

时间:2019-03-19 22:06:46

标签: reactjs typescript

目标是限制开发人员定义或访问对象没有的字段。或严格定义深度嵌套的对象或架构

const theme: iTheme = {
  palletes: {
    primary: {
      main: "white",
      dark: "black"
    },
    secondary: {}
  }
};

问题是我似乎无法告诉打字稿要求访问primary | secondary之一。我所做的是将两者都设为可选:

/* Below is my attempt of interface iTheme and iContextWithTheme */

type ColorKeys = "main" | "dark" | "light";
type ColorKeysFields = { [K in ColorKeys]?: string };

type Palletes = "primary" | "secondary";
interface iTheme {
  palletes: { [K in Palletes]?: ColorKeysFields };
}

interface iContextWithTheme {
  theme: Theme;
}

这几乎奏效,但我得到Object is possibly 'undefined'.ts(2532),然后“反应”被破坏了:

const color = (props: iContextWithTheme) => props.theme.palletes.primary.main;

/*
styled.div`
  color: ${props => props.theme.palletes.primary.main}
`;
*/

enter image description here

1 个答案:

答案 0 :(得分:0)

也许您想要这样的东西

type iTheme = {
  primary: ColorKeysField;
} | {
  secondary: ColorKeysField;
}