首页 / typescript / Use readonly to Avoid Errors Associated with Mutation
Placed on a property in an object type, readonly prevents assignments to that property:
interface PartlyMutableName {
readonly first: string;
last: string;
}
const jackie: PartlyMutableName = { first: 'Jacqueline', last: 'Kennedy' };
jackie.last = 'Onassis'; // OK
jackie.first = 'Jacky';
// ~~~~~ Cannot assign to 'first' because it is a read-only property
Typically, you’ll want to prevent assignments to all properties on an object. TypeScript provides a generic utility type, Readonly
interface FullyMutableName {
first: string;
last: string;
}
type FullyImmutableName = Readonly<FullyMutableName>;
// ^? type FullyImmutableName = {
// readonly first: string;
// readonly last: string;
// }
you can assign a mutable array to a readonly array, but not vice versa:
const a: number[] = [1, 2, 3];
const b: readonly number[] = a;
const c: number[] = b;
// ~ Type 'readonly number[]' is 'readonly' and cannot be
// assigned to the mutable type 'number[]'
When you give a parameter a read-only type (either readonly for an array or Readonly for an object type), a few things happen: