public
protected
private
- 접근(get), 설정(set) 2개가 자기 자신한테만 허용
- 해당 변수의 앞에 _ 를 붙이는 것이 관례
class UserInfo {
private _age: number;
private _phone: string;
constructor(age: number, phone: string){
this._age = age;
this._phone = phone;
}
get phone(): string {
return (
this._phone.slice(0, 3) + "-" +
this._phone.slice(3, 7) + "-" +
this._phone.slice(7, 12)
)
}
set phone(newPhone: string){
this._phone = newPhone
}
get age(){
return this._age
}
set age(newAge: number){
if(newAge <= 0) this._age = 0;
else this._age = newAge;
}
}
const user = new UserInfo(-25, "01012345678") // 0, 010-1234-5678
생성자 매개변수에 기본값을 설정할 수 있음
필드명에 ?를 붙여 null이여도 오류가 발생하지 않음
class LoginDataTransferObject {
public readonly ID;
private readonly _PW?;
constructor(ID: string, PW: string = "defualt password"){
this.ID = ID;
this._PW = PW;
}
}
const LoginDTO = new LoginDataTransferObject("hi");
// LoginDataTransferObject { ID: 'hi', _PW: 'defualt password' }
생성자를 이용한 클래스 선언 축약형
- 필드명과 생성자의 매개변수와 이름이 동일하게 세팅됨
class LoginDataTransferObject2 {
constructor(public readonly ID: string, public PW?: string){}
}
const LoginDTO2 = new LoginDataTransferObject2("hi");
🌈 클래스를 이용해 인스턴스를 만들 수 있지만 타입으로도 사용 가능
const testDto: testClass = new testClass("test");
변수 자체에 선언
let nameOrAge: string | number
nameOrAge = "danbi";
nameOrAge = 25;
인터페이스 활용
interface IName {
name: string;
}
interface IAge {
age: number;
}
type MyType = IName | IAge;
// function prtUnion(params: IName | IAge){
function prtUnion(params: MyType){
// name 정보가 들어왔을 때 로직
if("name" in params){
console.log(params.name)
}
// age 정보가 들어왔을 때 로직
if("age" in params){
console.log(params.age)
}
}
두 조건 모두 충족
interface IIName {
name: string;
}
interface IIAge {
age: number;
}
const nameAndAge: IName & IAge = {
name: "danbi",
age: 25
}