Promise

JuhyeokLee·2022년 2월 28일
0

Typescript

목록 보기
10/12
post-thumbnail

Promise에서의 Typescript

interface Contact {
  name: string;
  address: string;
  phones: PhoneNumberDictionary;
}

function fetchContacts(): Promise<Contact[]>{

  const contacts:Contact[] = [
    {
      name: 'Tony',
      address: 'Malibu',
      phones: {
        home: {
          num: 11122223333,
        },
        office: {
          num: 44455556666,
        },
      },
    },
    {
      name: 'Banner',
      address: 'New York',
      phones: {
        home: {
          num: 77788889999,
        },
      },
    },
    {
      name: '마동석',
      address: '서울시 강남구',
      phones: {
        home: {
          num: 213423452,
        },
        studio: {
          num: 314882045,
        },
      },
    },
  ];
  return new Promise(resolve => {
    setTimeout(() => resolve(contacts), 2000);
  });
}

Promise는 Typescript에서 타입이 Promise<resolve의 반환값> 형식으로 정의되어 있기 때문에 함수의 리턴타입은 Promise<Contact[]> 가 된다. Promise 안에 콜백함수에서 resolve의 타입은 이미 함수타입을 설정할 때 제네릭으로 표시했기 때문에 자동으로 타입추론이 돼 따로 표기할 필요는 없다.

  fetchData(): void {
    fetchContacts().then((response: Contact[]) => {
      this.contacts = response;
    });
  }

위와 같이 비동기 함수를 불러와 response를 사용하는 경우에 response에 대한 타입을 표기해도 좋고 이미 fetchContacts에서 타입이 Contact[]임을 선언했기 때문에 선언 안해도 괜찮다. 아래와 같은 내용이다.

function Array1():string[]{
  const arr:string[] = ['a','b','c'];
  return arr;
}
let arr1 = Array1(); // arr의 타입은 따로정해주지 않아도 string[]
profile
성장하는 개발자가 되겠습니다~

0개의 댓글

관련 채용 정보