Readonly
TypeScriptの型システムでは、インターフェース上の個々のプロパティを
readonly
としてマークすることができます。これにより、関数的に作業することができます(予期しない変更は良くありません)。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 🌹
もちろん
interface
とtype
の定義にreadonly
を使うこともできます: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
クラスプロパティを
readonly
として宣言することもできます。次のように、宣言箇所またはコンストラクタで初期化することができます。class Foo {
readonly bar = 1; // OK
readonly baz: string;
constructor() {
this.baz = "hello"; // OK
}
}
Readonly
型はT
型をとり、そのすべてのプロパティをreadonly
とマークします。以下にデモを示します: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
不変性(Immutabillity)を愛するライブラリの1つがReactJSです。たとえば、あなたの
Props
とState
には不変(immutable)であるとマークすることができます:interface Props {
readonly foo: number;
}
interface State {
readonly bar: number;
}
export class Something extends React.Component<Props,State> {
someMethod() {
// You can rest assured no one is going to do
this.props.foo = 123; // ERROR: (props are immutable)
this.state.baz = 456; // ERROR: (one should use this.setState)
}
}
しかし、Reactの型定義として、これらを
readonly
としてマークする必要はありません。Reactは既に内部でそれを行っています。export class Something extends React.Component<{ foo: number }, { baz: number }> {
// You can rest assured no one is going to do
someMethod() {
this.props.foo = 123; // ERROR: (props are immutable)
this.state.baz = 456; // ERROR: (one should use this.setState)
}
}
インデックスのシグネチャをreadonlyとしてマークすることもできます:
/**
* Declaration
*/
interface Foo {
readonly[x: number]: number;
}
/**
* Usage
*/
let foo: Foo = { 0: 123, 2: 345 };
console.log(foo[0]); // Okay (reading)
foo[0] = 456; // Error (mutating): Readonly