반응형

# TypeScript 

## 실습_전화번호부 애플리케이션

  • 내려받은 소스 바탕으로 진행.
  • address-book 터미널로 열어서 npm i 진행.

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "target": "es5",
    "lib": ["es2015", "dom", "dom.iterable"],
    "noImplicitAny": true,
    "strict": true,
    "strictFunctionTypes": true
  },
  "include": ["./src/**/*"]
}

동기 / 비동기 코드

  • promise : 비 동기 처리 시 사용.
// 동기 코드.
// function fetchItems() {
//     let items = ['a', 'b', 'c'];
//     return items;
// }

// let result = fetchItems();
// console.log(result);


// 비동기 코드
function fetchItems(): Promise<string[]> {
    let items: string[] = ['a', 'b', 'c'];
    return new Promise(function(resolve) {
        resolve(items);
    });
}

Map

// map
let heroes= [
    { name: 'Kim', age: 30 },
    { name: 'Jin', age: 130 },
];

heroes.map(function(hero) {
    return hero.name;   // ['Kim', 'Jin']
});

index.ts

interface PhoneNumberDictionary {
  [phone: string]: {
    num: number;
  };
}

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

enum PhoneType {
  Home = 'home',
  Ofiice = 'office',
  Studio = 'studio',
}

// api
// TODO: 아래 함수의 반환 타입을 지정해보세요.
// promise
function fetchContacts(): Promise<Contact[]> {
  // TODO: 아래 변수의 타입을 지정해보세요.
  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);  // 2초
  });
}

// main
class AddressBook {
  // TODO: 아래 변수의 타입을 지정해보세요.
  contacts: Contact[] = [];

  constructor() { // 초기화 코드
    this.fetchData();
  }

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

  /* TODO: 아래 함수들의 파라미터 타입과 반환 타입을 지정해보세요 */
  findContactByName(name: string): Contact[] {
    return this.contacts.filter(contact => contact.name === name);
  }

  findContactByAddress(address: string): Contact[] {
    return this.contacts.filter(contact => contact.address === address);
  }

  // phoneNumber : hone,  office, studio -> enum으로 제한.
  findContactByPhone(phoneNumber: number, phoneType: PhoneType): Contact[] {
    return this.contacts.filter(
      contact => contact.phones[phoneType].num === phoneNumber
    );
  }

  addContact(contact: Contact): void {
    this.contacts.push(contact);
  }

  // map api
  displayListByName(): string[] {
    return this.contacts.map(contact => contact.name);
  }

  displayListByAddress(): string[] {
    return this.contacts.map(contact => contact.address);
  }
  /* ------------------------------------------------ */
}

new AddressBook();
반응형

+ Recent posts