在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
A
const ORIGIN = { x: 0, y: 0 } // works ORIGIN.x = 1
If you don't want user able to change it: const ORIGIN: { readonly x: number, readonly y: number } = { x: 0, y: 0 } // Typescript complian // Cannot assign to 'x' because it is a read-only property. ORIGIN.x = 1
Better way: const ORIGIN = { x: 0, y: 0 } as const // Typescript complian // Cannot assign to 'x' because it is a read-only property. ORIGIN.x = 1
But `as const` doesn't enforce in runtime. If we do want to prevent mutate the object, we can do: const ORIGIN = Object.freeze({ x: 0, y: 0 } as const) // Typescript complian // Cannot assign to 'x' because it is a read-only property. ORIGIN.x = 1
|
请发表评论