functionfoo(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を使うこともできます:
typeFoo= {readonly bar:number;readonly bas:number;}// Initialization is okaylet foo:Foo= { bar:123, bas:456 };// Mutation is notfoo.bar =456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property
interfaceProps {readonly foo:number;}interfaceState {readonly bar:number;}exportclassSomethingextendsReact.Component<Props,State> {someMethod() {// You can rest assured no one is going to dothis.props.foo =123; // ERROR: (props are immutable)this.state.baz =456; // ERROR: (one should use this.setState) }}
exportclassSomethingextendsReact.Component<{ foo:number }, { baz:number }> {// You can rest assured no one is going to dosomeMethod() {this.props.foo =123; // ERROR: (props are immutable)this.state.baz =456; // ERROR: (one should use this.setState) }}
let foo:ReadonlyArray<number> = [1,2,3];console.log(foo[0]); // Okayfoo.push(4); // Error: `push` does not exist on ReadonlyArray as it mutates the arrayfoo =foo.concat([4]); // Okay: create a copy
classPerson { firstName:string="John"; lastName:string="Doe";getfullName() {returnthis.firstName +this.lastName; }}constperson=newPerson();console.log(person.fullName); // John Doeperson.fullName ="Dear Reader"; // Error! fullName is readonly
constとの相違点
const
変数参照に利用するものである
他の値を再度割り当てることはできない
readonly
プロパティに利用するものである
エイリアシングによってプロパティが変更されることがありえる
説明のためのサンプル1:
constfoo=123; // variable referencevar bar: {readonly bar:number; // for property}
説明のためのサンプル2:
let foo: {readonly bar:number;} = { bar:123 };functioniMutateFoo(foo: { bar:number }) {foo.bar =456;}iMutateFoo(foo); // The foo argument is aliased by the foo parameterconsole.log(foo.bar); // 456!
interfaceFoo {readonly bar:number;}let foo:Foo= { bar:123};functioniTakeFoo(foo:Foo) {foo.bar =456; // Error! bar is readonly}iTakeFoo(foo); // The foo argument is aliased by the foo parameter