解决 TypeScript 报错:A computed property name in an interface must refer to an ...

374 阅读1分钟

当我定义了一个变量:

export const FieldsMap = {
  stack: "Stack",
  name: "Name",
};

并且尝试定义一个 interface 接口,在其中用计算属性:

export interface SelectAStackType {
  [FieldsMap.stack]: "",
  [FieldsMap.name]: ""
}

很遗憾,TypeScript 给我报了一个错误:A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)

不过同样有提示说使用计算属性必须要用字面量类型或者唯一的 symbol 类型

其实这个很好理解,这样定义主要是防止我们在中途去篡改对象里面的值:

const PROPS = {
  VALUE: 'value'
}
// 中途篡改属性值
PROPS.VALUE = 'aha!';

export default class Main extends Vue {
  readonly [PROPS.VALUE]: string
}

那么引用一个随时都可能的值作为属性,那么就有可能出现找不到属性的情况,因为通过定义 字面量类型 或者 唯一的 symbol 类型 去确保这个值不会被改变。

因为,我们两种解决方案:

  1. 定义唯一的 symbol 类型:
const level: unique symbol = Symbol();

interface MyInterface {
    [level]?: string;
}
  1. 定义为字面量类型。要把一个对象变量字面量类型,我们需要类型推断 as 的帮助
export const FieldsMap = {
  stack: "Stack" as "Stack",
  name: "Name" as "Name",
};

也可以使用 const 推断,一步到位:

export const FieldsMap = {
  stack: "Stack",
  name: "Name",
} as const;

我是 Pandy,一个喜欢英语的程序猿 👨‍💻

关注公众号 Yopth,回复「加群」,加入「英文技术翻译互助群」,我们加入一起充电英语 🔌

Reference

[1] A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. #4605 [2] Literal Types