Microsoft/TypeScript

Error message displays computed name '[attr]' instead of key value

Open

#57,653 创建于 2024年3月5日

在 GitHub 查看
 (3 评论) (0 反应) (0 负责人)TypeScript (6,726 fork)batch import
Experience EnhancementHelp WantedSuggestion

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

🔎 Search Terms

computed property, error message

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about computed properties

⏯ Playground Link

https://tsplay.dev/WyV2bw

💻 Code

type Unit =
  | {
      name: string;
      stength: number;
    }
  | {
      name: string;
      magic: number;
    };

const createUnit = (
  name: string,
  attr: "strength" | "magic",
  power: number,
): Unit => {
  return attr === "strength"
    ? { name, [attr]: power } // <-- error here
    : { name, [attr]: power };
};

🙁 Actual behavior

Error message displays "Object literal may only specify known properties, and '[attr]' does not exist in type 'Unit'".

🙂 Expected behavior

Error message should display that "strength" doesn't exist on Unit. (and possibly even recommend "stength" instead)

Additional information about the issue

No response

贡献者指南