오버로딩

  • TypeScript 에 있는 메서드 중 하나로 선언한 타입은 다르지만 같은 함수 명으로 사용할 수 있게 해주는 기능
  • 각 경우에 대해 새 함수를 만들 필요 없이 입력 인수에 따라 함수의 다른 구현을 제공하려는 경우에 특히 유용

 

예시

Interface User{
    id : number;
    name: string;
    age: number;
}

Interface UserQuery{
    id : number;
    name?: string;
    age?: number;
}


function findPerson(name: string): Person[];
function findPerson(age: number): Person[];
function findperson(userQuery: UserQuery) : Person;
function findPerson(query: string | number| UserQuery): Person[]| Person[]|Person {
  if (typeof query === "string") {
    // search by name
    return [{ id: 1, name: query, age: 30 },{ id: 10, name: query, age: 20 },...];
  } 
  if (typeof query === "number") {
    // search by age
    return [{ id: 15, name: "Alice", age: query }, { id: 3, name: "Bob", age: query }];
  }
  if (typeof query === "UserQuery"){
    // search by id with name or age
    return {id: queay, name: "Joey", age:30}
  }
}

 

 

 

참고자료

https://medium.com/@bobjunior542/master-function-overloading-in-typescript-with-these-simple-tips-169bea017aa4

Promise<void> : 각 작업이 성공적으로 완료되었을 때 추가적인 반환값 없이 완료되는 것을 의미

 

값을 삭제하는 요청처럼 특별하게 반환되는 값이 없을 때 사용

단순히 특정 요청이 완료되는 것을 확인하는 경우 사용

extends

사용하는 이유 

기존 클래스의 속성과 메서드를 물려받아 새로운 클래스를 정의하기 위해서 (interface에도 사용가능)

 

이점

- 중복되는 코드가 없어진다.

- 코드의 재사용성이 높아진다.

- 확장성있는 코드를 만들 수 있다.

- 유지 및 보수가 쉬워진다.

- 클래스들간의 관계를 계층적으로 형성하여 시스템의 이해를 도울 수 있다.

 

단점

- 부모에서 발생한 변경이 모든 자식들에게 영향을 끼친다.

- 상속을 너무 많이 사용하면 구조의 복잡도가 올라가 오히려 시스템의 이해가 어려질 수도 있다.

 

사용하는 경우

- 기능확장이 필요할때

- 공통적으로 가지는 기능이 있어야 할때

 

사용하는 방식 

class Person {
  constructor(private firstName: string, private lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  getFullName(): string {
    return `사람이름 출력`;
  }
  
  describe(): string {
     return `This is ${this.firstName} ${this.lastName}.`;
  }
}

 

class Employee extends Person {
  constructor(firstName, lastName, private jobTitle: string) {
    super(firstName, lastName);
    this.jobTitle= jobTitle;
  }
  
  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  
  describe(): string {
    return super.describe() + `I'm a ${this.jobTitle}.`;
  }
  
  
}

부모 클래스 (Person) 에 있는 Constructor를 호출하기 위해서, 자식 클래스 (Employee)에서 super() 을 사용해야 한다.

 

const newEmployee = new Employee('Joey','Lim','Back-end Developer');

console.log(newEmployee.getFullName());
// Joey Lim
console.log(newEmployee.describe());
// This is Joey Lim. I am a Back-end Developer

 

 

참고 사이트

https://www.typescripttutorial.net/typescript-tutorial/typescript-inheritance/

 

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

[ TS ] 오버로딩  (0) 2024.05.09
[ TS ] Promise<void> 의미  (0) 2024.05.07
[ TS ] interface : 필터링하기  (0) 2024.04.01
[TS] 유틸리티 타입 (Utility Types): Keyof, Partial  (0) 2024.03.08
[TS] 제네릭 ( Generics )  (0) 2024.03.08

 

객체의 속성과 타입을 정의

interface Student{
    korean: number;
    english: number;
    math: number;
}

 

 

이제 Student 를 이용해서 객체(object)를 생성

const joey: Student ={
    korean: 90,
    english: 100,
    math: 80,
}

 

90점 이상인 과목이 몇개 인지 확인

const countOverNinetyScore = Object.values(joey).filter(score => score>90).length;

 

이제부터 오류가 시작된다....

에러 1. Object.values 는 "es2017" 이후 부터 적용되는 문법이여서 에러 발생

 

keys 를 사용하여 변경!

const countOverNinetyScore = Object.keys(joey).filter(key => joey[key] >= 90).length;

 

에러 2. key 가 뭔데??? any 타입일 수도 있는데  막쓰면 안된다는 내용의 에러발생

TSError: ⨯ Unable to compile TypeScript:
- error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Student'.
No index signature with a parameter of type 'string' was found on type 'Student'.
       joey [key]>= 90).length

..... 

 

구글링을 통하여 해결법 발견

const countOverNinetyScore = Object.keys(joey).filter(key 
					=> joey[key as keyof Student]>= 90).length

 

위 코드에서 "joey[ key as keyof Student]" 을 사용하는 이유
key가 Student 인터페이스에서 유효한 키임을 TypeScript 컴파일러에 알려줘야 하기 때문이다.
그냥 joey[key] 를 사용하면 TypeScript 컴파일러는 key 가 Student 인터페이스의
모든 가능한 키 중 하나라는 것을 보장할 수 없으므로 타입 체킹 오류를 발생시킨다.

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

[ TS ] Promise<void> 의미  (0) 2024.05.07
[ TS ] 상속 : extends, super(),  (0) 2024.05.05
[TS] 유틸리티 타입 (Utility Types): Keyof, Partial  (0) 2024.03.08
[TS] 제네릭 ( Generics )  (0) 2024.03.08
[ TS ] 추상 class  (0) 2024.03.08

+ Recent posts