【问题标题】:Typescript - Type 'string' is not assignable to union type of stringsTypescript - 类型\'string\'不可分配给联合类型的字符串
【发布时间】:2023-02-15 22:45:42
【问题描述】:

我有一个组件获取联合类型的道具:

export const RoleTag = ({ roleType }: { roleType: "BA" | "BM" | "BP" | "FR" | "RM" }) => {
    return (
        <Tag variant={ROLE_TAGS[roleType]} size="small" className="w-8 mr-2 rounded">
            {rolleType}
        </Tag>
    );
};

Tag 组件也将 variant 定义为 union:

export interface TagProps extends HTMLAttributes<HTMLSpanElement> {
  children: React.ReactNode;
  /**
   * Changes visual profile of tag
   */
  variant:
    | "warning"
    | "warning-filled"
    | "error"
    | "error-filled"
    | "info"
    | "info-filled"
    | "success"
    | "success-filled"
    | "neutral"
    | "neutral-filled"
    | "alt1"
    | "alt1-filled"
    | "alt2"
    | "alt2-filled"
    | "alt3"
    | "alt3-filled";
  /**
   * @default "medium"
   */
  size?: "medium" | "small" | "xsmall";
}

我正在使用 ROLE_TAG 常量计算变体:

export enum RolleType {
    BM = "BM",
    BP = "BP",
    BA = "BA",
    RM = "RM",
    FR = "FR",
}

export const ROLE_TAGS = {
    [RolleType.BM]: "success",
    [RolleType.BP]: "alt1",
    [RolleType.BA]: "alt1",
    [RolleType.RM]: "alt3",
    [RolleType.FR]: "alt3",
};

但是,在当前设置下,我得到了一个 Typescript 错误:

TS2322: Type 'string' is not assignable to type '"success" | "alt1" | "alt3" | "warning" | "warning-filled" | "error" | "error-filled" | "info" | "info-filled" | "success-filled" | "neutral" | "neutral-filled" | "alt1-filled" | "alt2" | "alt2-filled" | "alt3-filled"'.

我在这里做错了什么,我该如何解决?

【问题讨论】:

    标签: typescript


    【解决方案1】:
    export const ROLE_TAGS = {
        [RolleType.BM]: "success",
        [RolleType.BP]: "alt1",
        [RolleType.BA]: "alt1",
        [RolleType.RM]: "alt3",
        [RolleType.FR]: "alt3",
    };
    

    由于这没有明确的类型,因此打字稿会推断出一个。当它看到字符串时,它假设类型应该是string,所以推断类型是:

    {
        BM: string;
        BP: string;
        BA: string;
        RM: string;
        FR: string;
    }
    

    由于属性的类型是string,因此有关特定值的信息将丢失。因此,当您尝试在需要更具体值的地方使用 string 时,您会收到错误消息。

    如果您希望打字稿在其推理中更严格,您可以添加 as const 来告诉打字稿这些值永远不会改变:

    export const ROLE_TAGS = {
        [RolleType.BM]: "success",
        [RolleType.BP]: "alt1",
        [RolleType.BA]: "alt1",
        [RolleType.RM]: "alt3",
        [RolleType.FR]: "alt3",
    } as const;
    
    // Inferred type:
    //{
    //    readonly BM: "success";
    //    readonly BP: "alt1";
    //    readonly BA: "alt1";
    //    readonly RM: "alt3";
    //    readonly FR: "alt3";
    //}
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2021-09-21
      • 2022-01-17
      • 2021-08-19
      • 1970-01-01
      • 2021-07-14
      相关资源
      最近更新 更多