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: []
};
CodePudding user response:
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: [
// ...
]
};