简体   繁体   English

TypeScript 对象类型断言不起作用

[英]TypeScript object type assertion doesn’t work

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: []
};

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.当您使用as [[typename]]表示法时,不会执行类型检查,因为您手动告诉编译器您确定这是正确的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM