readonlyプロパティとパラメータープロパティ
readonlyとコンストラクターのプロパティ省略記法を使います。
「readonlyプロパティとパラメータープロパティ」はCoddyKit上の無料TypeScript Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはTypeScript Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 TypeScript Academyコースには全4レッスンが含まれています。
ようこそ
クラスプロパティでのreadonly
class Invoice {
readonly invoiceId: string;
constructor(id: string) { this.invoiceId = id; }
}
const inv = new Invoice('INV-001');
// inv.invoiceId = 'INV-002'; // Error!インターフェースでのreadonly
interface Point { readonly x: number; readonly y: number; }
const p: Point = { x: 5, y: 10 };
// p.x = 0; // Errorパラメータプロパティ
class Product {
constructor(
public name: string,
public price: number,
private sku: string
) {} // no need to write this.name = name; etc.
}readonlyパラメータプロパティ
class Config {
constructor(
public readonly host: string,
public readonly port: number = 3000
) {}
}宣言時の初期化
class AppVersion {
readonly version: string = '1.0.0';
readonly buildDate: Date = new Date();
}readonlyとconst
const API_KEY = 'secret'; // block variable
class Service {
readonly key: string = API_KEY; // class property
}Readonlyオブジェクト型
interface User { name: string; age: number; }
const frozen: Readonly<User> = { name: 'Alice', age: 30 };
// frozen.name = 'Bob'; // Errorreadonlyはディープフリーズではない
class Team {
readonly members: string[] = [];
}
const t = new Team();
t.members.push('Alice'); // Allowed — the array itself is mutable!
// t.members = []; // Error — can't reassign the propertyパラメータプロパティで定型コードを削減
// Without parameter properties (verbose)
class A {
private x: number;
constructor(x: number) { this.x = x; }
}
// With parameter properties (concise)
class B {
constructor(private x: number) {}
}パラメータプロパティを避ける場面
確認問題
まとめ
よくある質問
「readonlyプロパティとパラメータープロパティ」レッスンは無料ですか?
はい。「readonlyプロパティとパラメータープロパティ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、TypeScript Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 TypeScript Academyコースには全4レッスンが含まれています。
「readonlyプロパティとパラメータープロパティ」で何を学びますか?
readonlyとコンストラクターのプロパティ省略記法を使います。 ブラウザで直接実行するハンズオンコードでTypeScript Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
TypeScript Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのTypeScript Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「readonlyプロパティとパラメータープロパティ」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このTypeScript Academyレッスンでコードを書いて実行できますか?
はい。すべてのTypeScript Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- TypeScriptのクラスとコンストラクター
- public、private、protected修飾子
- readonlyプロパティとパラメータープロパティ
- クラスによるInterfaceの実装