[TS] 기본 문법 실습(1)

optional Properties

interface Config {
  color: string,
  width?: number
}

function createSqure(config: Config): { color: string; area: number } {
  return {
    color: config.color,
    area: 100 * (config.width ? config.width : 1), 
  }
}

const config = {
  color : 'red'
};

createSqure(config);

width 프로퍼티를 optional 프로퍼티로 변경하였기 때문에 config객체 생성시 color 프로퍼티만 정의하여도 오류가 생기지 않는다.

interface 확장

interface Animal {
  makeSound(): void
}

interface Dog extends Animal {  
  run(): void
}

class BullDog implements Dog {
    makeSound(): void {
        console.log('멍멍');
    }
    
    run(): void {
        console.log('달리기');
    }
}

const bullDog = new BullDog();
bullDog.makeSound(); // 멍멍 출력
bullDog.run(); // 달리기 출력

Dog interface에 Animal interface를 확장하였고 BullDog 클래스에서 Dog를 implements를 하였기 때문에 클래스 내부에 makeSound(), run() 메서드가 구현되어 있어야 한다.

Generic class

class Stack<T> {
  private data: Array<T> = [];
  
  push(item: T) {
    this.data.push(item);
  }
  
  pop(): T | undefined {
    return this.data.pop();
  }
}

const numberStack = new Stack<number>();

numberStack.push(100);
console.log(numberStack.pop());

Generic을 이용한다면 컴파일시에 타입을 적용시켜 Number 또는 다른타입만을 허용하는 stack을 생성할 수 있다.

pop 메서드의 반환타입에는 undefined를 추가하여 stack이 비어있는 상황을 고려하였다.

Generic 제약조건

Generic을 사용하면서 특정 속성만을 허용할수도 있다.

const printMessage = <T extends string | number | boolean>(message: T): void => {
    console.log(message);  
}

printMessage<number>(5);

printMessage<boolean>(true);
// [Errors in code]
// Type 'boolean' does not satisfy the constraint 'string | number'.

extends 키워드로 string과 number타입으로 제한할 수 있다.
boolean타입은 허용되는 타입이 아니기 때문에 에러가 발생한다.

기본 타입말고도 interface를 이용하여 제한할 수 있다.

interface Lengthwise {
  length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

loggingIdentity(3);
c
// Argument of type 'number' is not assignable to parameter of type 'Lengthwise'
loggingIdentity({ length: 10, value: 3 });

Using Type Parameters in Generic Constraints

keyof 키워드를 사용하여 아래와 같이 다른 타입 매개변수로 제한된 타입 매개변수를 선언할 수 있다.

하나의 예시로 객체 타입 매개변수로 제한된 타입매개변수를 선언하는 예시를 들어본다면 아래와 같이 구현할 수 있다.

function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
  return obj[key];
}
 
let x = { a: 1, b: 2, c: 3, d: 4 };
 
getProperty(x, "a");


getProperty(x, "m");
// [Errors in code]
// Argument of type '"m"' is not assignable to parameter of type '"a" | "b" | "c" | "d"'.

변수 x 타입에 대해서 m이라는 프로퍼티는 존재하지않기 때문에 에러가 발생한다.


Reference

좋은 웹페이지 즐겨찾기