diff --git a/src/app.ts b/src/app.ts index 5798ae6..0311a71 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,25 +1,21 @@ -const person: { - name: string, - age: number, - hobbies: string[]; - role: (number | string)[]; -} = { - name: 'Maximilian', - age: 30, - hobbies: ['Sports', 'Cooking'], - role: [2, 'author'] -}; +function combine(n1: number | string, n2: number | string) { + let result; + if (typeof n1 === 'number' && typeof n2 === 'number') { + result = n1 + n2; + } else if (typeof n1 === 'string' && typeof n2 === 'string') { + result = n1 + n2; + } else { + result = n1.toString() + n2.toString(); + } // 해결 방법: if문으로 typeof로 각 타입들이 무엇인지 식별한 후 연산을 적용한다. 연산이 적용되지 않는 타입들은 모두 string으로 형변환 후 연산을 시켜주면 된다. 따라서 유니온 타입으로 여러 타입을 유연하게 사용할 수 있지만 이것들을 활용할 때는 정확히 어떤 타입을 받는지에 관한 로직이 보통 함수나 클래스 구조에 많이 필요하다. + return result; +} +// Ts가 염려하는 error의 근원은 아래와 같다. +// const b1: boolean = true; +// const b2: boolean = false; +// console.log(b1 + b2); -person.role.push('admin'); -person.role[1] = 10; -person.role = [0, 'admin', 'user']; +const CombineAges = combine(20, 30); +console.log(CombineAges); -//any는 어떤 타입이든 허용하는 타입이다. 어떻게 보면 유연하다고 느껴지질지 모르겠지만 타입스크립트의 장점을 전혀 활용하지 못하기에 좋은 방법은 아니다. -let favoriteActivities: any[]; -favoriteActivities = ['Sports', 1]; //이렇게 배열에 마구잡이로 서로 다른 타입을 넣어도 아무런 에러가 일어나지 않는다. - -console.log(person.name); - -for (const hobby of person.hobbies) { - console.log(hobby); -} \ No newline at end of file +const CombineNames = combine('Max', 'Anna'); +console.log(CombineNames); diff --git a/src/basics.ts b/src/basics.ts index 98000c7..7019098 100644 --- a/src/basics.ts +++ b/src/basics.ts @@ -1,4 +1,4 @@ -function add(n1: number, n2: number, showResult: boolean, phrase: string) { +function addTemplate(n1: number, n2: number, showResult: boolean, phrase: string) { const result = n1 + n2; //result는 number라고 추론을 한다. if (showResult) { console.log(result + phrase); @@ -13,4 +13,29 @@ const printResult = true; const resultPhrase = 'Result is: '; // resultPhrase = 0; //error -> 타입 추론으로 resultPhrase는 string이다. 따라 0이라는 number타입을 할당할 수 없다. -add(number1, number2, printResult, resultPhrase); \ No newline at end of file +addTemplate(number1, number2, printResult, resultPhrase); + +const person: { + name: string, + age: number, + hobbies: string[]; + role: (number | string)[]; +} = { + name: 'Maximilian', + age: 30, + hobbies: ['Sports', 'Cooking'], + role: [2, 'author'] +}; + +person.role.push('admin'); +person.role[1] = 10; +person.role = [0, 'admin', 'user']; + +let favoriteActivities: any[]; +favoriteActivities = ['Sports', 1]; + +console.log(person.name); + +for (const hobby of person.hobbies) { + console.log(hobby); +}