타입스크립트 readonly tuple 예제
타입스크립트(TypeScript)의 readonly tuple은 튜플( Tuple )에 저장된 값을 생성 이후 변경하지 못하도록 제한하는 타입 표현 방식이다.
readonly가 적용된 튜플은 각 요소를 읽을 수는 있지만, 기존 요소의 값을 다른 값으로 변경하거나 새로운 요소를 추가, 삭제하는 작업이 제한된다.
튜플(tuple)은 배열과 비슷하지만 요소의 개수, 위치, 각 위치의 타입을 명확하게 표현할 수 있고, 여기에 readonly를 적용하면 임의로 값을 수정하지 못하도록 제한할 수 있다.
값의 변경을 타입 수준에서 제한하기 때문에 개발 과정에서 데이터를 수정하는 문제를 줄이는 데 도움이 된다.
readonly는 타입스크립트의 타입 검사 단계에서 변경을 하지 못하도록 제한하는 기능이다.
⊙
const point: readonly [number, number] = [10, 20];⊙
const user: [string, number] = ["Kim", 30];⊙
user[0] = "Lee";
user[1] = 31;⊙
user[0] = 100;
// TypeScript 오류⊙
readonly [타입1, 타입2, 타입3]⊙
const point: readonly [number, number] = [10, 20];⊙
console.log(point[0]); // 10
console.log(point[1]); // 20⊙
point[0] = 100;
// 오류: 읽기 전용 속성이므로 할당할 수 없음⊙
let mutablePoint: [number, number] = [10, 20];
mutablePoint[0] = 100; // 가능⊙
const readonlyPoint: readonly [number, number] = [10, 20];
readonlyPoint[0] = 100; // 오류⊙
[number, number]
readonly [number, number]⊙
const point = [10, 20];
point[0] = 100;⊙
const point = [10, 20];
point = [30, 40];
// 오류
point[0] = 30;⊙
const point1: readonly [number, number] = [10, 20];
const point2 = [10, 20] as const;
point1[0] = 30; // 오류
point2[0] = 30; // 오류
readonly [number, number]
readonly [10, 20]⊙
const point: readonly [number, number] = [10, 20];
const point = [10, 20] as const;⊙
function printPoint(
point: readonly [number, number]
) {
console.log(point[0], point[1]);
}⊙
function printPoint(
point: readonly [number, number]
) {
const x = point[0];
const y = point[1];
console.log(x, y);
}⊙
function printPoint(
point: readonly [number, number]
) {
point[0] = 999;
// TypeScript 오류
}⊙
function showPoint(
point: readonly [number, number]
) {
console.log(point);
}⊙
const point: [number, number] = [10, 20];
showPoint(point);⊙
const point = [10, 20] as const;
function changePoint(
point: [number, number]
) {
point[0] = 100;
}
changePoint(point);
// 오류⊙
const config: readonly [string, number] = [
"localhost",
3000,
];
config[1] = 8080;
// TypeScript 오류
댓글
댓글 쓰기