TypeScriptで、読み込み専用・変更不可にするにはconstやreadonlyを使用します。
constとreadonlyは使う場面が異なり、
プロパティにはreadonly
変数にはconst
を使用します。
プロパティにconstを使うと文法エラーになります。
interface Point {
const x: number; // error TS1005: ';' expected.
const y: number; // error TS1005: ';' expected.
}
変数にreadonlyを使ってもエラーになります。
readonly greeting: string = "hello"; //error TS1128: Declaration or statement expected.
正しくは、プロパティにはreadonly
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error TS2540: Cannot assign to 'x' because it is a constant or a read-only property.
変数にはconstを使います。
const greeting: string = "hello";
greeting = ""; // error TS2540: Cannot assign to 'greeting' because it is a constant or a read-only property.