当前位置:网站首页>解决 TypeScript 报错:A computed property name in an interface must refer to an expression whose type ...
解决 TypeScript 报错:A computed property name in an interface must refer to an expression whose type ...
2022-07-22 08:10:00 【Pandy : )】
当我定义了一个变量:
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 类型 去确保这个值不会被改变。
因为,我们两种解决方案:
- 定义唯一的 symbol 类型:
const level: unique symbol = Symbol();
interface MyInterface {
[level]?: string;
}
- 定义为字面量类型。要把一个对象变量字面量类型,我们需要类型推断
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
边栏推荐
猜你喜欢
学点编程:防失业“疫苗”
RK3399平台开发系列讲解(内存篇)15.33、为什么可用内存会远超物理内存?
【案例分享】配置IS-IS的路由渗透功能
【Excle】生成guid和datetime导入测试数据到数据库
Allegro如何导入高清Logo、二维码、防静电标识等图片以及汉字
Understanding and learning of dates
Concurrent model values actor and CSP
Rk3399 platform development series explanation (memory chapter) 15.33. Why does the available memory far exceed the physical memory?
需要达到什么水平,程序员才能顺利拿到20k月薪无压力?
日期类的理解学习
随机推荐
基础SQL Server 操作问题——仅当使用了列表并且IDENTITY_INSERT为ON时,才能为表中的标识列制定显示值
Methodology (I): how to quickly learn a programming language
Distributed (I) what is sacred about distributed systems, base and cap?
Evolution of multi activity in different places
Fibonacci series of Niuke network
go flag包
力扣练习——28 拼接最大数
The problem of the result set returned by MySQL stored procedure
[exception] generate guid and datetime, import test data to the database
1.4.1 好多好多道符(cin/cout解绑,O3优化)
43. 字符串相乘
力扣练习——21 有序矩阵中的第 k 个最小数组和
go对接口简单理解
How does boss direct hire write an excellent resume?
十七、C函数指针与回调函数
JS String charAt substring() substr slice toUpperCase toLowerCase indexOf
Hblock盘活企业级存储市场
VCs and Verdi learning records
GBase8s数据库子查询中的 UNION
基于信誉管理模型的矿工类型鉴别机制设计