created at 2023/07/14 11:18:43
updated at 2023/08/03 03:48:20
Object.freeze
and TypeScript's Readonly
JavaScript 的Object.freeze
和 TypeScript 的只读 - Dale L. Jefferson (dalejefferson.com)
JavaScript’s Object.freeze()
function provides runtime immutability (at a minor performance cost). You have a 100% guarantee your array or object will not change underneath you.
typescript
// Readonly<Type>
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: '',
};
// todo.title = "";
// This utility is useful for representing assignment expressions that
// will fail at runtime (i.e. when attempting to reassign properties of a frozen object).
javascript
// javascript里的 Object.freeze();
const user = Object.freeze({ name: 'Carl Menger', age: 18, gender: 'meal' });
user.age = 20; // Runtime Error
typescript
// typescript 里的Readonly
interface User {
readonly name: string;
readonly age: number;
readonly gender: string;
}
const u: User = {
name: 'JAY',
age: 20,
gender: 'MEAL',
};
u.age = 10; // Compile error
typescript
const p: Readonly<User> = Object.freeze({
name: 'July',
age: 20,
gender: 'meal',
});
p.age = 30;