sungyup's.

typescript / TypeScript Basics / 1.3 TypeScript Demo Project

1.3TypeScript Demo Project

데모 프로젝트로 알아보는 타입스크립트 예시

데모 프로젝트 시작하기

이번 포스트에선 타입스크립트로 투자 계산기 프로그램을 만들어보자.

우선, 새로운 폴더에서 tsc --init을 실행해 tsconfig.json 파일을 생성한다.

다음으로, calculator.ts 파일을 생성한다. 우리는 이 파일에서 초기 투자 금액(initial amount), 연간 추가 투자 금액(annual contribution), 예상 수익률(expected return) 및 투자 기간(duration)을 받아 매년 투자 수익을 계산할 것이다.

필요한 타입 정의하기

만약 우리의 주요 함수인 calculateInvestment에 4가지 파라미터를 모두 넣는다면 아래와 같이 복잡해질 것이다:

typescript
function calculateInvestment(initialAmount: number, annualContribution: number, expectedReturn: number, duration: number){ // 계산하기... };

따라서 보다 가독성이 좋은 방법은 파라미터를 객체로 받고 해당 객체의 타입을 정의하는 것이다.

typescript
type InvestmentData = { initialAmount: number; annualContribution: number; expectedReturn: number; duration: number; }; function calculateInvestment(data: InvestmentData){ // 계산하기... };

함수를 정의할때 파라미터 외에도 반환 값의 타입 또한 정의할 수 있다. 우리는 총 금액(total amount), 총 투자 금액(total contributions) 및 총 수익(total interest earned)를 속성으로 가지는 객체들의 배열(연간)을 반환할 것이다.

이 때도 역시 앞선 InvestmentData처럼 객체의 타입을 지정할 수 있는데, 나아가 에러 상황에선 에러 메시지를 띄우기 위해 string 타입 또는 이 객체들의 배열을 반환한다고 가정하자.

typescript
type InvestmentResult = {
year: string;
totalAmount: number;
totalContributions: number;
totalInterestEarned: number;
}
type CalculationResult = InvestmentResult[] | string;
function calculateInvestment(data: InvestmentData): CalculationResult {
// result[]
}

로직 작성하기

예외 처리하기

데이터를 받아 destructuring을 한 후, 비정상적인 인풋의 경우 에러 메시지를 반환한다. 예를 들어, 초기 투자 금액이 0보다 작거나 투자 기간이 음수거나 한다면 잘못된 인풋이 들어온 것이므로 해당 내용에 맞는 에러 메시지를 반환해야 한다.

typescript
function calculateInvestment(data: InvestmentData):CalculationResult { const { initialAmount, annualContribution, expectedReturn, duration } = data; if(initialAmount < 0 ) { return "Initial amount must be greater than 0"; } if(duration <= 0){ return "Duration must be greater than 0"; } if(expectedReturn < 0){ return "Expected return must be greater than 0"; } // ... }

투자 금액 계산 로직 작성하기

투자 금액 및 수익은 아래와 같이 계산할 수 있다. 결과 값들은 InvestmentResult[] 형태여야하므로, 변수에 해당 타입을 지정하고 빈 배열을 할당한 후 for문을 순회하며 데이터를 추가한다.

typescript
function calculateInvestment(data: InvestmentData):CalculationResult { // ... 예외처리... let total = initialAmount; let totalContributions = 0; let totalInterestEarned = 0; const annualResults: InvestmentResult[] = []; for(let i = 0; i < duration; i++){ total = total * (1 + expectedReturn); totalInterestEarned = total - totalContributions - initialAmount; totalContributions += annualContribution; total += annualContribution; annualResults.push({ year: `Year ${i + 1}`, totalAmount: total, totalContributions, totalInterestEarned, }); } return annualResults; }

출력 함수 작성

우리가 작성한 함수는 값을 구하는 함수이다. 이 함수를 통해 계산한 값을 확인하기 위해 출력 함수를 아래와 같이 작성할 수 있다. 핵심은 results라는 CalculationResult 타입의 데이터를 받는다는 것으로, 반환은 없기 때문에 typescript가 자동으로 void를 반환하는 것으로 추론한다. 이 함수는 데이터를 받아 콘솔에 결과 값을 로깅만 한다.

typescript
function printResults(results: CalculationResult){ if(typeof results === "string"){ console.log(results); } else { for(const yearEndResult of results){ console.log(yearEndResult.year); console.log(`Total: ${yearEndResult.totalAmount}.toFixed(0)`); console.log(`Total Contributions: ${yearEndResult.totalContributions}.toFixed(0)`); console.log(`Total Interest Earned: ${yearEndResult.totalInterestEarned}.toFixed(0)`); console.log("--------------------------------"); } } }