TypeScript 배우기 — 궁극의 초보자 가이드: 객체 지향 프로그래밍

33559 단어


1. 객체 지향 프로그래밍



우리가 알고 있듯이 JavaScript는 (PHP, Java, C++, C# ...)과 같은 다른 프로그래밍 언어처럼 classes의 개념을 가지고 있지 않습니다.
ES6를 사용하여 classes를 정의할 수 있지만 constructor functionprototypal inheritance를 생성하기 위한 구문 설탕일 뿐입니다.
OOP에서 TypeScript를 보자.

1- 클래스 및 객체 생성 :




class Account {
  id: number;
  owner: string;
  balance: number;

  constructor(id: number, owner: string, balance: number) {
    this.id = id;
    this.owner = owner;
    this.balance = balance;
  }

  deposit(amount: number): void {
    if (amount > 0) {
      this.balance += amount;
    }

    throw new Error("Invalid amount");
  }
}

let account = new Account(1, "zineddine", 100);

account.deposit(100);

console.log(typeof account); // object
console.log(account instanceof Account); // true

/*

always make sure to use instanceof property to check if 
an object is an instance of a class

*/

Note : function 안에 class 키워드를 사용하여 function 를 선언할 수 없습니다. stand-alone function 를 선언할 때만 사용하십시오.

2- 읽기 전용 및 선택적 속성:




class User {
  readonly id: number;
  name: string;
  email: string;
  nickname?: string; // optional property

  constructor(id: number, name: string, email: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
}

let user = new User(1, "zineddine", "[email protected]");
user.id = 12; // Cannot assign to 'id' because it is a read-only property


3- 액세스 제어 키워드:




class Account {
  /*
    public # by default
    private
    protected
  */

  id: number;
  private _balance: number;

  constructor(id: number, balance: number) {
    this.id = id;
    this._balance = balance;
  }

  deposit(amount: number): void {
    if (amount > 0) {
      // assume we want also to log the transaction
      this._balance += amount;
    }

    throw new Error("Invalid amount");
  }

  private calculateTax(amount: number): number {
    return amount * 0.1;
  }

  getBalance(): number {
    return this._balance;
  }
}

let account = new Account(1, 100);
account._balance -= 50; // Property '_balance' is private and only accessible within class 'Account'


4- 매개변수 속성 및 게터 및 세터:




class Account {
  nickname?: string; // optional property

  constructor(
    public readonly id: number,
    public owner: string,
    private _balance: number
  ) {}

  get balance(): number {
    return this._balance;
  }

  set balance(value: number) {
    if (value < 0) {
      throw new Error("Balance cannot be negative");
    }
    this._balance = value;
  }
}

let account = new Account(1, "zineddine", 100);

console.log(account.balance); // 100
account.balance = -100; // throws error
account.balance = 100; // OK


5- 색인 서명:



색인 서명은 dynamic properties의 멋진 이름일 뿐입니다.

class NameByNumber {
  // index signature property
  [name: string]: number;
}

let nameByNumber = new NameByNumber();

nameByNumber.John = 1;
// nameByNumber.['John'] = 1;
// nameByNumber.John = '1'; Type 'string' is not assignable to type 'number'
nameByNumber.Jane = 2;
nameByNumber.Bob = 3;

console.log(nameByNumber.John); // 1


6- 정적 멤버:




class Ride {
  private static _activeRides: number = 0;

  start() {
    Ride._activeRides++;
  }

  end() {
    Ride._activeRides--;
  }

  static get activeRides() {
    return Ride._activeRides;
  }
}

let ride1 = new Ride();
let ride2 = new Ride();

ride1.start();
ride2.start();

console.log(Ride.activeRides); // 2


7- 상속 및 메서드 재정의:




class Person {
  constructor(public firstName: string, public lastName: string) {}

  get fullName() {
    return this.firstName + " " + this.lastName;
  }

  walk() {
    console.log("Walking");
  }
}

class Student extends Person {
  constructor(firstName: string, lastName: string, public id: number) {
    super(firstName, lastName);
  }

  override walk() {
    super.walk();
    console.log("Walking on the stairs");
  }

  override get fullName() {
    return "Student : " + super.fullName;
  }
}

let student = new Student("John", "Doe", 123);

console.log(student.fullName);
student.walk();

/*

  Walking
  Walking on the stairs

*/

console.log(student instanceof Person); // true


8- 다형성:




// parent class , base class , super class
class Person {
  protected steps: number = 0;

  constructor(public firstName: string, public lastName: string) {}

  get fullName() {
    return this.firstName + " " + this.lastName;
  }
}

// child class , sub class , derived class
class Student extends Person {
  constructor(firstName: string, lastName: string, public id: number) {
    super(firstName, lastName);
  }

  override get fullName() {
    return "Student : " + super.fullName;
  }
}

class Teacher extends Person {
  constructor(firstName: string, lastName: string, public id: number) {
    super(firstName, lastName);
  }

  override get fullName() {
    return "Teacher : " + super.fullName;
  }
}

function printName(persons: Person[]) {
  for (let person of persons) {
    console.log(person.fullName);
  }
}

printName([
  new Person("John", "Doe"),
  new Student("Jane", "Doe", 123),
  new Teacher("John", "Doe", 123),
]);

/*

John Doe
Student : Jane Doe
Teacher : John Doe

*/


9- 추상 클래스 :




abstract class Shape {
  constructor(public color: string) {}

  abstract render(): void;
}

class Circle extends Shape {
  constructor(public radius: number, color: string) {
    super(color);
  }

  override render(): void {
    console.log("Circle");
  }
}

let shape = new Shape("red"); // Cannot create an instance of an abstract class


10- 인터페이스:




interface Calender {
  name: string;
  addEvent(event: string): void;
  removeEvent(event: string): void;
}

interface CloudCalender extends Calender {
  sync(): void;
}

class GoogleCalender implements CloudCalendar {
  constructor(public name: string) {}

  addEvent(event: string): void {
    console.log(`Adding ${event} to GoogleCalendar`);
  }
  removeEvent(event: string): void {
    console.log(`Removing ${event} from GoogleCalendar`);
  }
  sync(): void {
    console.log("Syncing GoogleCalendar");
  }
}

Note :에서 TypeScript, interfacestype aliases는 서로 바꿔서 사용할 수 있습니다.
둘 다 물체의 모양을 설명하는 데 사용할 수 있습니다.

interface Person {
  name: string;
}

let person: Person = {
  name: "Zineddine",
};

type User = {
  name: string;
};

let user: User = {
  name: "Zineddine",
};


이번 챕터는 여기까지입니다!

Github 링크 : TypeScript-Fundamentals-in-One-Place

좋은 웹페이지 즐겨찾기