| readonly와 생성자
readonly
필드 에 readonly 를 붙이면 오로지 Read 만 되고 수정은 안된다
class LogicDataTransferObject{
public readonly ID;
private readonly _PW;
constructor(ID: string, PW: string){
this.ID = ID;
this._PW = PW;
}
set PW(newPW: string){
this._PW = PW;
}
}
const LoginDTO = new LogicDataTransferObject("hi","1234");
LoginDTO.PW = "set";
console.log(LoginDTO);
생성자
class LogicDataTransferObject{
public ID;
public PW;
constructor(ID: string, PW: string){
this.ID = ID;
this.PW = PW;
}
}
위 코드와 아래 코드는 같은 코드이다
class LogicDataTransferObject{
constructor(public ID: string, public PW: string){}
}
필드와 생성자를 생성자안에 한번에 다 적을 수 있다.
만약 비밀번호 값이 들어올수도있고 안들어올수도 있다면
class LogicDataTransferObject{
public ID;
public PW?;
constructor(ID: string, PW?: string){
this.ID = ID;
if (PW) this.PW = PW;
}
}
const LoginDTO = new LogicDataTransferObject("hi");
console.log(LoginDTO);
if(PW)를 안넣어주면 undefined가 나오게 된다
class LogicDataTransferObject{
public ID;
public PW?;
constructor(ID: string, PW?: string){
this.ID = ID;
this.PW = PW;
}
}
const LoginDTO = new LogicDataTransferObject("hi");
console.log(LoginDTO);
생성자로 줄여서 쓰면
class LogicDataTransferObject{
constructor(public ID: string, public PW?: string){
}
}
const LoginDTO = new LogicDataTransferObject("hi");
console.log(LoginDTO);
두번째 인자를 넣지않아도 생성이 잘 된다
그리고 파라미터 기본값도 넣을 수 있다
class LogicDataTransferObject{
constructor(public ID: string, public PW: string = "12345"){
}
}
const LoginDTO = new LogicDataTransferObject("hi");
console.log(LoginDTO);
const LoginDTO1 = new LogicDataTransferObject("hi","bye");
console.log(LoginDTO1);
pw값을 입력안하면 12345가 디폴트값으로 설정되고
값을 넣으면 그값이 들어가게된다
생성자에도 readonly를 넣을 수 있다
class LogicDataTransferObject{
constructor(public readonly ID: string, public readonly PW: string = "12345"){
}
}
const LoginDTO = new LogicDataTransferObject("hi");
LoginDTO.ID="change";
에러가 난다
클래스타입
참고로 클래스는
new 클래스명()로 인스턴스를 만들수있지만,
타입으로도 쓸수 있다.
아래와 같이 user에 new UserInfo로 할당하고 동시에 타입을 UserInfo로 달 수 있다.
class UserInfo{
constructor(public readonly ID: string, public readonly PW: string = "12345"){
}
}
const user:UserInfo = new UserInfo("hi");
반응형
'웹 개발 > #️⃣ TypeScript' 카테고리의 다른 글
TS | key와 같이 쓰는 타입 (0) | 2023.06.03 |
---|---|
TS | 대수타입 -union, intersection (0) | 2023.06.01 |
TS | 클래스 - 접근제한자와 getter setter (0) | 2023.06.01 |
TS | null과 undefined (0) | 2023.05.30 |
TS | never (1) | 2023.05.30 |