typescript

23.01.29 Union Type

슈팅스타제제 2023. 1. 29. 23:42

Union type (공용체?!)을 주로 사용하는 목적은 파라미터는 하나인 함수에서 한 가지 이상 타입을 인자로 받고 싶을 때 사용한다. 

 

class rangeValidationBase {
  constructor(private start: number, private end: number) {}
  protected rangeCheck(value: number): boolean {
    return value >= this.start && value <= this.end;
  }
  protected getNumber(value: string): number {
    return new Number(value).valueOf();
  }
}

 

위 클래스를 상속해서 문자열과 숫자만 들어오도록 확인하는 함수를 포함한 클래스를 만들어주는데

이때, 여기서 this.isInRangeString method 를 쓰면 재귀?!

1. 각각의 타입을 분리하여 처리하는 메서드

class separateTypeRangeValidation extends rangeValidationBase {
  isInRangeString(value: string): boolean {
    return this.rangeCheck(this.getNumber(value));
  }
  isInRangeNumber(value: number): boolean {
    return this.rangeCheck(value);
  }
}

2. 위 클래스에서 유니온 타입을 이용하여 간결하게 바꾼 코드

class anyRangeValidation extends rangeValidationBase {
  isInRange(value: string | number): boolean {
    if (typeof value === "number") {
      return this.rangeCheck(value);
    }
    return this.rangeCheck(this.getNumber(value));
  }
}

하지만 함수에서 한번에 너무 많은 타입을 처리한다면 그것도 좀 그럼

하나의 함수에서 너무 많은 일을 하고 있지는 않은지 체크해서 코드를 더 작게 분리하도록 하자~!

 

tsconfig 에 --strictNullChecks 옵션을 추가하면 null 이나 undefined 를 변수에 할당할 수 없다. 

'typescript' 카테고리의 다른 글

23.02.05 왜 super call?  (0) 2023.02.05
23.01.29 Access Modifier  (1) 2023.01.30
22.02.24 default parameter  (0) 2022.02.24
22.02.18 interface extends 안될 때, Omit  (0) 2022.02.20
21.12.23 [typescript] setState props로 넘길 때 Dispatch  (1) 2021.12.23