front-end/TypeScript
Typescript class 타입 지정 constructor, prototype
Hoon0211
2024. 2. 23. 10:09
728x90
1. 필드값 타입 지정하기
1. class 내부에는 모든 자식 object에게 속성을 만들수있습니다.
2. class 내부 중괄호 안에 변수 처럼 작성하면 됩니다.
3. 타입스크립트로 인한 타입을 지정이 가능합니다.
class electronics {
name :string = 'TV';
model :number = 20240223
}
let home = new electronics();
console.log(home);
//model:20240223
//name:"TV"
2. constructor 타입지정
1. 필드 값을 설정해야 됩니다.
class electronics {
constructor() {
this.name = name;
this.model = model;
}
}
// 에러 발생 Error : Property 'name' does not exist on type 'electronics'
2. 파라미터의 타입을 지정해야 됩니다.
class electronics {
name: string;
model: number;
constructor(name, model) {
this.name = name;
this.model = model;
}
}
// 에러 발생
3. 파라미터를 넣고 싶으면 constructor로 해야 됩니다.
class electronics {
name: string;
model: number;
constructor(name: string, model: number) {
this.name = name;
this.model = model;
}
}
let home = new electronics('TV', 20240223);
3. prototype 사용하기
1. prototype 사용하기
electronics.prototype.test = function(){
// 내용
}
2. class 내부에서도 사용이 가능하다
class electronics {
name: string;
model: number;
constructor(name: string, model: number) {
this.name = name;
this.model = model;
}
// prototype
test(model:number){
console.log('모델명 ' + model)
}
}
let home = new electronics('TV', 20240223);
home.test(20240223)
728x90