0
type ConfigItem<T> = {
  label: string;
  name: keyof T;
};

type P1 = {
  E1: {
    A: "xl",
    B: "xl",
    C: "xl",
    D: "xl",
  },
  E2: {
    AA: "xxl",
    BB: "xxl",
    CC: "xxl",
    DD: "xxl",
  },
};

export const Configs = {
  X1: [
    { label: "ax", name: "A2" }, // ⬅️ Why is it not restricted?
    { label: "bx", name: "B" },
    { label: "cx", name: "C" },
    { label: "dx", name: "D2" }, // If the last one is not in E1, an error is reported.
  ] as ConfigItem<P1["E1"]>[],
  X2: [
    // ...
  ]
};

An error is reported only if the last item in the array has the wrong value type.

When the last item is correct, the previous item is incorrect, no error will be reported.

"typescript": "^4.4.4"

[UPDATE]: Is that the only way to do it?

const X1: ConfigItem<P1["E1"]> = [
  { label: "ax", name: "A2" },
  { label: "bx", name: "B" },
  { label: "cx", name: "C" },
  { label: "dx", name: "D" },
];

export const Configs = {
  X1,
  X2: []
};
2
  • What behavior are you expect ? Please provide more context to the problem you have Commented Oct 20, 2021 at 10:00
  • 3
    You shouldn't be using a type assertion at all; you want the compiler to check the types, not just trust you: tsplay.dev/we0veW Commented Oct 20, 2021 at 10:01

1 Answer 1

1

When you are using the as [[typename]] notation no type checking is going to be performed as you are telling the compiler manually that you are certain this is correct.

What you want to do to enable type checking is:

type ConfigItem<T> = {
  label: string;
  name: keyof T;
};

type P1 = {
  E1: {
    A: "xl",
    B: "xl",
    C: "xl",
    D: "xl",
  },
  E2: {
    AA: "xxl",
    BB: "xxl",
    CC: "xxl",
    DD: "xxl",
  },
};

export const Configs: {X1: ConfigItem<P1["E1"]>[], X2: any /*define next here*/} = {
  X1: [
    { label: "ax", name: "A2" },
    { label: "bx", name: "B" },
    { label: "cx", name: "C" },
    { label: "dx", name: "D2" },
  ],
  X2: [
    // ...
  ]
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.