클래스, 함수, 인터페이스 를 다양한 타입으로 재사용 가능

코드를 재사용할 수 있다는 측면에서 유용한 수단

 

여러가지 타입을 사용하는 예시

function getSize(arr: number[] | string[] | boolean[]): number{
   return arr.length;
}

const arr1 = [1,2,3];
getSize(arr1)

const arr2 = ["a", "b", "c"];
getSize(arr2)

const arr3 = [true, true, false];
getSize(arr3)

 

Generic을 사용한 경우

함수

function getSize<T>(arr: T[]): number{
   return arr.length;
}

const arr4 = [1,2,3];
getSize<number>(arr4)

const arr5 = ["a", "b", "c"];
getSize<string>(arr5)

const arr6 = [true, true, false];
getSize<boolean>(arr6)

 

interface

interface Mobile<T>{
   name: string;
   price: number;
   option: T;
}

const m1: Mobile<object> = {
   name: "s24",
   price: 10000,
   option:{
      color: "red",
      coupon: false,
   }
}

const m2: Mobile<{color: string; coupon: boolean}> = {
   name: "s24",
   price: 10000,
   option:{
      color: "red",
      coupon: false,
   }
}

const m3: Mobile<string> = {
   name: "s24",
   price: 10000,
   option: "good"
}

 

 

특정 인터페이스만 허용하는 함수

interface User{
   name: string;
   age: number;
}

interface Car{
   name: string;
   color: string;
}

interface Book{
   price: number;
}

const user: User = {name: 'a', age: 30};
const car: Car = {name: 'bmw', color: 'red'};
const book: Book = {price: 3000};

function showName<T extends {name: string}>(data:T): string {
   return data.name;
}

showName(user);
showName(car);
showName(book);// name 이 없으모 컴파일 에러 발생

 

참고강의:

https://www.youtube.com/watch?v=pReXmUBjU3E&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=7

추상적으로 class 를 정의 해 놓고

클래스를 할당 한후 구체적인 내용을 적는 방식

new 를 이용하여 사용할 수 없다.

 

abstract class Car {
     color: string;
     constructor(color: string){
        this.color = color;
     }
     start(){
        console.log('start');
     }
     abstract doSomething():void;
}

// const car = new Car("red") // error

class Bmw extends Car {
   constructor(color: string){
      super(color);
   }
   doSomething(){
      alert(3);
   }
}

객체지향 언어에는 Constructor 라는 것이 있다.

Constructor 을 이용하여 코드를 좀더 명확하고 깔끔하게 향상 시킬수 있다.

 

모든 Class 는 Constructor 를 가질 수 있다.

이 Constructor 는 Class 의 인스턴트,

즉, 클라스로 부터 객체를 생성할 때 호출되는 함수이며, 

"객체의 초기화를 담당한다."

 

사용예시

class Employee{
   fullName: string;
   age: number;
   jobTitle: string;

   // 위에 있는 파라메터들을 초기화
   constructor(fullName: string, age:number, jobTitle: string){
      this.fullName = fullName;
      this.age = age;
      this.jobTitle = jobTitle;
   }

   printEployeeDetails = (): void => 
   {
      console.log( `${this.fullName} 의 직없은 ${this.jobTitle}`);
   }
}

let employee1: Employee = new Employee('정우', 30, 'staff');
employee1.fullName = '헨리'
employee1.printEployeeDetails();

 

Access Modifiers

클라스 속 멤버변수(프로퍼티)와 메소드에 적용될 수 있는 키워드를 클라스 외부로 부터의 접근을 통제

-> 버그를 줄이고 코드의 안정성을 높일 수 있다.

 

<종류>

- Public (default): 외부에서 접근 가능

- Private : 클라스 내에서만 접근가능, 외부에서는 접근 불가능 (비공개 멤버)

- Protected : 클라스 내부, 그리고 상속받은 자식 클라스에서 접근가능

 

* private 을 나타낼때 #을 사용 가능 (ex) #fullName: string , this.#fullName

Access Modifiers 예시

class Employee{
   private fullName: string;
   age: number;
   jobTitle: string;

   // 위에 있는 파라메터들을 초기화
   constructor(fullName: string, age:number, jobTitle: string){
      this.fullName = fullName;
      this.age = age;
      this.jobTitle = jobTitle;
   }

   printEployeeDetails = (): void => 
   {
      console.log( `${this.fullName} 의 직없은 ${this.jobTitle}`);
   }
}

let employee1: Employee = new Employee('정우', 30, 'staff');

console.log(employee1.fullName) // <-- 컴파일 에러 발생
employee1.fullName = '헨리' // <-- 컴파일 에러 발생 

employee1.printEployeeDetails();

 

그러면 어떻게 private 로 설정된 객체에 접근이 가능할까?

=> TypeScript 에서 Getter와 Setter 라는 것을 제공하고 있다.

 

Get 과 Set 키워드를 사용하여 Getter와 Setter 선언

 

<예시>

class Employee{
   private _fullName: string; 
   // underscore를 이용하여 private 멤버임을 나타내준다. private 멤버라는 것을 나타내기 위한 룰
   age: number;
   jobTitle: string;

   // 위에 있는 파라메터들을 초기화
   constructor(fullName: string, age:number, jobTitle: string){
      this._fullName = fullName;
      this.age = age;
      this.jobTitle = jobTitle;
   }
   
   // getter 사용
   get fullName(){
       return this._fullName;
   }
   // setter 사용
   set fullName(value:string){
       this._fullName = value;
   }

   printEployeeDetails = (): void => 
   {
      console.log( `${this._fullName} 의 직없은 ${this.jobTitle}`);
   }
}

let employee1: Employee = new Employee('정우', 30, 'staff');

console.log(employee1.fullName) // <-- getter 사용하여 컴파일 에러 사라짐
employee1.fullName = '헨리' // <-- setter 사용하여 컴파일 에러 사라짐

employee1.printEployeeDetails();

 

 

Class 에 Access Modifiers 를 이용하여 코드를 더 간결하게 하는 예시

class Employee{
   // 객체가 생성될 때, 컨스트럭터의 매개변수로 전달된 값은, 객체의 프로퍼티 값으로 자동으로 그 값이 초기화 되고 할당됨
   constructor(
      private _fullName: string,
      private _age: number,
      public jobTitle: string){
   }
   
   // getter 사용
   get fullName(){
       return this._fullName;
   }
   // setter 사용
   set fullName(value:string){
       this._fullName = value;
   }

   printEployeeDetails = (): void => 
   {
      console.log( `${this._fullName} 의 직없은 ${this.jobTitle}`);
   }
}

 

참고 강의 :
https://www.youtube.com/watch?v=sPM94o5_WVU&list=PLJf6aFJoJtbUXW6T4lPUk7C66yEneX7MN

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] 제네릭 ( Generics )  (0) 2024.03.08
[ TS ] 추상 class  (0) 2024.03.08
[TS] 교차 타입 (Intersection Types)  (0) 2024.03.06
[TS] 유니온 Union Types  (0) 2024.03.06
[TS] 리터럴 타입 (Literal Types)  (0) 2024.03.06

여러개의 타입을 하나로 합쳐서
필요한 모든 기능을 가진 하나의 타입을 만들때 사용

 

예시

interface Car {
  name: string;
  start(): void;
} 

interface Mobile {
  name: string;
  color: string;
  price: number;
}

const mobileCar: Mobile & Car = {
  name: "타요",
  start() {},
  color: "green",
  price: 10000,
};

 

참고강의: 
https://www.youtube.com/watch?v=QZ8TRIJWCGQ&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=5

 

유니온 타입은 하나의 변수에 여러 개의 타입을 정의하고 싶은 경우에 사용을 한다.

 

유니온 타입 예시

interface Car {
  name: "car";
  color: string;
  start(): void;
} 

interface Mobile {
  name: "mobile";
  color: string;
  call(): void;
}

// 식별 가능한 유니온 타입
function getGift(gift: Car | Mobile){
  console.log(gift.color);
  if(gift.name == "car") {
    gift.start(); // gift에 마우스를 올리면 car 인 걸 알수 있음
  } else{
    gift.call(); // gift에 마우스를 올리면 mobile 인 걸 알수 있음
  }
}

 

참고강의:https://www.youtube.com/watch?v=QZ8TRIJWCGQ&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=5

+ Recent posts