https://joey0203.tistory.com/369 에서 내용 추가.

 

장점

  • 객체가 변경되지 않으므로 예측가능한 상태 유지 가능
  • 이해하기 쉽고 안정적인 서비스 개발에 도움이 된다.

 

단점

  • 객체의 값이 할당될 때마다 새로운 객체가 필요하다.

 

구현 방법

const 사용

const helloWorld = "Hello World";

helloWorld = "Hi world"; // Cannot assign to 'helloWorld' because it is a constant.

 

Object.freez() 이용

const myDefinitelyConstantObject = Object.freeze({
  msg: "Hello World",
});

// Cannot assign to 'msg' because it is a read-only property.
myDefinitelyConstantObject.msg = "Hi"


const myFrozenArray = Object.freeze(["Hi"]);

//Property 'push' does not exist on type 'readonly string[]'.
myFrozenArray.push("World");

 

readonly 이용

class UserDetails { 
        readonly name: string 
        readonly city: string 
        readonly phoneNo: number 
        constructor(name: string, city: string, phoneNo: number){ 
            this.name = name 
            this.city = city 
            this.phoneNo = phoneNo 
        }   
} 
      
const user1 = new UserDetails("ABCD", "XYZ", 1234567890); 
const user2 = new UserDetails("APPLE", "PQR", 1269785100);

 

 

 

 

참고자료

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] index signature  (0) 2024.08.03
[ TS ] DTO object 구현  (0) 2024.08.03
[ TS ] 비밀번호 암호화 (bcypt)  (0) 2024.06.13
[ TS ] tsconfig.json 의 내용 정리  (0) 2024.06.08
[ TS ] 오버로딩  (0) 2024.05.09

+ Recent posts