[Typescript] 클래스

rondido·2023년 2월 22일
0

Typescript

목록 보기
2/6
post-thumbnail

클래스

  • Javascript에서는 ES2015의 새로운 문법
  • TypeScript에서의 클래스 기능은 C#에서 유래된 것이 많다.
  • 일부 기능은 TS에서만 존재하는 고유 문법으로 컴파일 후에 사라진다.
class Person {
    //필드
    // -일종의 속성
    // - public 으로 사용 가능.
    
    name : string;
    age : number;
    readonly location:string ='Korea'
}

//클래스를 인스턴스화
//교유한 메모리를 가지고 있는 클래스로부터 파생된 것
// 실제로 생성된 후 메모리에 올라간다.
const p = new Person();

생성자

class Person {
    //필드
    // -일종의 속성
    // - public 으로 사용 가능.
    
    name : string;
    age : number;
    readonly location:string ='Korea'
    //생성자
    //초기화 담당
    constructor(name: string ,age: number){
        this.name = name;
        this.age = age;
    }
}

//클래스를 인스턴스화
//교유한 메모리를 가지고 있는 클래스로부터 파생된 것
// 실제로 생성된 후 메모리에 올라간다.
const p1 = new Person('park',123);
const p2 = new Person('Poco',100);

console.log(p1);

console.log(p2);

메서드

class Person {
    //필드
    // -일종의 속성
    // - public 으로 사용 가능.
    
    name : string;
    age : number;
    readonly location:string ='Korea'
    //생성자
    //초기화 담당
    constructor(name: string ,age: number){
        this.name = name;
        this.age = age;
    }

    // 메서드
    // 객체(클래스)는 행동을 뜻함.
    introduce(): string{
        return `${this.name}의 나이는 ${this.age}`
    }
}

//클래스를 인스턴스화
//교유한 메모리를 가지고 있는 클래스로부터 파생된 것
// 실제로 생성된 후 메모리에 올라간다.
const p1 = new Person('park',123);
const p2 = new Person('Poco',100);

console.log(p1.introduce());

console.log(p2.introduce());

getter setter

//gette & setter

// 필드에 접근할 권한을 가진 제어자
// getter O / setter X => 속성은 자동으로 읽기 전용
// setter 매개변수의 타입 X / getter의 반환 타입에서 추론

// private 속성은 .연산자로 접근할 수 있다.

class Person1 {
    name: string;
    private _age: number;

    constructor(name: string, age: number){
        this.name = name;
        this._age = age;
    }

    get age(){
        if(this._age === 0){
            return'설정되지 않았습니다.'
        }
        return `나이는 ${this._age}세로 추정`
    }
    set age(age){
        if(typeof age === 'number'){
        this._age = age

        }
        this._age = 0
    }
}

const p3 = new Person1('park',123);
console.log(p3.age); //private이라서 볼 수가 업다
console.log(p3.name);
  • ts getter && setter 사용하는 과정에서 ECMA5이상에서만 지원한다는 에러 발견
💡 tsconfig.json에서 compilerOptions에다가 "target": "es5"을 추가해줌

extends

// 상속
// 확장

class 기본{
    result(){
        return 'Base'
    }
}

class 파생 extends  기본{
    result(): string {
        return 'Derived'
    }
}

const de = new 파생();

de.result() //Derived

super

  • 기본 클래스 호출 시 사용
  • 생성자에서 this 사용 전 호출 해야함
// super
// 기본 클래스 호출시 사용
// 생정자에서 this 사용 전 호출 해야함

class Animal{
    name :string
    constructor(name:string){
        this.name = name;
    }
    sayName(){
        return`동물의 이름은${this.name}`
    }
    
}

class Person3 extends Animal{
    constructor(name: string){
        super(name)
    }
    sayName(){
        return `${super.sayName()}사람의 이름은${this.name}` //동물의 이름은 park 사람의 이름은 park
    }
}

const person = new Person3('park'); //park이 constructor안으로 들어감

접근 제어자

  • 속성과 메서드에 접근을 제한할 수 있다.
  • 클래스 내부 구현 정보를 적당히 공개하여 일부분만 노출시킨다.
    • API와 비슷한 흉내를 낼 수 있다.
    • 타입 시스템을 이용해 규칙을 강제할 수 있다.
제어자설명
public어디서나 접근가능(기본값)
protected해당 클래스와 서브클래스에서만 접근 가능
private해당 클래스의 인스턴스에서만 접근 가능
class People{
    public name: string
    private age: number
    protected gender:'M' | 'F'

    constructor(name:string, age:number, gender:'M' | 'F'){
        this.name= name
        this.age =age
        this.gender = gender
    }

    sayName(){
        return `이름 ${this.name} 입니다`
    }
    // 서브 클래스 공유 가능
    protected sayAge(){
        return `나이는 ${this.age}`
    }
    // 자기 자신의 클래스에만 사용 가능
    private sayGender(){
        return ` 성별 타입은 ${this.gender}`
    }
}

class Me extends People{
    constructor(name:string, age:number, gender:'M' | 'F'){
        super(name,age,gender)        
    }

    sayInfo(){
        return `${super.sayName()} ${super.sayAge()} ` //protecd인데 접근 가능 //gender는 접근할 수 없다.
    }
}

const p = new People('park', 99 ,'M')

static

  • 클래스의 속성과 메서드를 new로 인스턴스화 하지 않고 호출할 수 있다.
  • 접근 제어자를 활용할 수 있다.
  • 몇가지 정적 이름을 사용할 수 없다.
    • 클래스는 그 자체로 new로 호출할 수 있는 함수이기 때문
class StaticClass{
    private static type = 'type'
    //static name = 'name'  static 이름이 충돌한다.

    static getType(){
        return StaticClass.type
    }
}

//StaticClass.type  static을 사용함으로써 type에 접근 가능 private으로 변경 시 접근 불가능
StaticClass.getType() // 접근가능
//StaticClass.test()  static으로 메서드도 접근 가능

readonly

  • javascript에서는 사용할 수 없는 문법
class ReadOnlyClass{
    name : string
    readonly age : number
    constructor(name:string,age:number){
        this.name = name;
        this.age = age
    }
    // setAge(newAge: number){
    //     this.age = newAge
    // } 여기도 에러 발생
}

const r = new ReadOnlyClass('park', 99);

r.name = 'ppp' //너무 쉽게 값을 변경할 수 있다.

r.age = 30; // readonly가 되면서 에러가 발생

추상 클래스

  • abstract 를 선언한 클래스로 직접 인스턴스화 될 수 없는 클래스
  • 직접 인스턴스화 될 수 없지만 extends 후 파생된 클래스를 인스턴스화하도록 유도
  • 추상 클래스는 구현된 메서드를 포함시킬 수 있다.
  • abstract 선언한 메서드는 파생된 클래스에서 메서드를 구현해야 함.
abstract class AnimalClass{
    //선언된 메서드
    
    abstract hello() :string
    

    // 구현된 메서드
    run(){
        return this.hello + 'run'
    }
}

// 직접 인스턴스화가 될 수 없다.
//const animal = new AnimalClass()
//파생된 클래스가 되면 인스턴스화 할 수 있다.
class AnimalC1 extends AnimalClass {
    // abstract hello(str: string) :string를 통해 메서드를 강제한다.
    hello(){
        return 'people'
    }
}

class Dog extends Animal{
    hello(){
        return 'Dog'
    }

}

const people = new AnimalC1()

parameter properties


class People1{
    // public name:string, 
    //     private age:number,
    //     protected gender:'M' | 'F'
    constructor(
        public name:string, 
        private age:number,
        protected gender:'M' | 'F'){
        this.name= name
        this.age =age
        this.gender = gender
    }

    sayName(){
        return `이름 ${this.name} 입니다`
    }
    // 서브 클래스 공유 가능
    protected sayAge(){
        return `나이는 ${this.age}`
    }
    // 자기 자신의 클래스에만 사용 가능
    private sayGender(){
        return ` 성별 타입은 ${this.gender}`
    }
}

class Me1 extends People1{
    constructor(name:string, age:number, gender:'M' | 'F'){
        super(name,age,gender)        
    }

    sayInfo(){
        return `${super.sayName()} ${super.sayAge()} ` //protecd인데 접근 가능 //gender는 접근할 수 없다.
    }
}

const pe = new People1('park', 99 ,'M')

메서드 오버라이딩

class Man{
    run(){
        return 'Animal이 달리다'
    }
}

class Cat extends Man{
    run(){
        return 'Cat가 달리다'
    }
}

class Woman extends Man{
    run(){
        return 'Woman이 달린다'
    }
}

const w = new Woman();
const m = new Man();
const c = new Cat();

console.log(m.run()); // man이 달린다.
console.log(c.run()); // Cat이 달린다.
console.log(w.run()); // Woman이 달린다.
profile
개발 옆차기

0개의 댓글