타입스크립트에서 가리키는 모듈이라는 개념은 ES6+의 Modules
개념과 유사하다.
모듈은 전역 변수와 구분되는 자체 유효 범위를 가지며 export
, import
와 같은 키워드를 사용하여 다른 파일에서 접근할 수 있다.
// types.ts
export interface Todo {
title: string;
checked: boolean;
}
// app.ts
import { Todo } from './types.ts';
var item: Todo = {
title: '타입 공부하기',
checked: true,
}
// types.ts
interface PhoneNumberDictionary {
[phone: string]: {
num: string;
};
}
interface Contact {
name: string;
address: string;
phones: PhoneNumberDictionary;
}
enum PhoneType {
Home = 'home',
Office = 'office',
Studio = 'studio'
}
export {
PhoneNumberDictionary,
Contact,
PhoneType
};
// functions.ts
import { Contact } from './types';
export 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);
});
}
// index.tst
import { Contact, PhoneType } from './types';
import { fetchContacts } from './functions';
// main
class AddressBook {
contacts: Contact[] = [];
constructor() {
this.fetchData();
}
fetchData(): void {
fetchContacts().then(response => {
this.contacts = response;
});
}
findContactByName(name: string): Contact[] {
return this.contacts.filter(contact => contact.name === name);
}
findContactByAddress(address: string): Contact[] {
return this.contacts.filter(contact => contact.address === address);
}
findContactByPhone(phoneNumber: string, phoneType: PhoneType): Contact[] {
return this.contacts.filter(
contact => contact.phones[phoneType].num === phoneNumber
);
}
addContact(contact: Contact): void {
this.contacts.push(contact);
}
displayListByName(): string[] {
return this.contacts.map(contact => contact.name);
}
displayListByAddress(): string[] {
return this.contacts.map(contact => contact.address);
}
}
const addrBook = new AddressBook();