mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-24 12:36:23 +00:00
1.3 KiB
1.3 KiB
date | id | title |
---|---|---|
2020-10-05 | c0bc64a7-f2dc-4e2e-afb9-5dbc63eb8287 | Readonly |
Introduction
TypeScript's type system allows you to mark
individual properties on interfaces,
types and
class properties as readonly
.
Examples
interface
function foo(config: {
readonly bar: number,
readonly bas: number}) {// ..
}
let config = { bar: 123, bas: 123 };
foo(config);
// You can be sure that `config` isn't changed 🌹
type
type Foo = {
readonly bar: number;
readonly bas: number;
}
// Initialization is okay
let foo: Foo = { bar: 123, bas: 456 };
// Mutation is not
foo.bar = 456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property
class property
class Foo {
readonly bar = 1; // OK
readonly baz: string;
constructor() {
this.baz = "hello"; // OK
}
}
type Foo = {
bar: number;
bas: number;
}
type FooReadonly = Readonly<Foo>;
let foo: Foo = {bar: 123, bas: 456};
let fooReadonly: FooReadonly = {bar: 123, bas: 456};
foo.bar = 456; // Okay
fooReadonly.bar = 456; // ERROR: bar is readonly