Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ 서진 ] #5

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

[ 서진 ] #5

wants to merge 3 commits into from

Conversation

se0jinYoon
Copy link

@se0jinYoon se0jinYoon commented Nov 7, 2023

  • 제목은 [ 이름 ] 으로 작성해주세요!

🌮 무엇을: 계산기 로직 구현

  • 타입스크립트로 DOM 요소 접근하기
  • 계산기 함수 구현
  • click 이벤트 함수 구현

🌮 어떻게:

  • DOM 요소 접근
    answer.innerText = ... 접근 시 에러 발생 방지를 위해 HTMLElement = document.getElementById('answer')!; 와 같이 !를 추가해 null일 수 없음을 지정
const userInput1: HTMLInputElement = document.getElementById('userInput1') as HTMLInputElement;
const userInput2: HTMLInputElement = document.getElementById('userInput2') as HTMLInputElement;
const operationType: HTMLSelectElement = document.getElementById('operationType') as HTMLSelectElement;
const answer: HTMLElement = document.getElementById('answer')!;
const resultBtn: HTMLButtonElement = document.getElementById('resultBtn') as HTMLButtonElement;
  • 계산기 함수
    switch-case 문으로 구현
function calculate(firstInput:number, secondInput:number, operator:string):number {
    let result:number = 0;
    switch(operator) {
        case "sum":
            result = firstInput + secondInput;
            break;
        case "sub":
            result = firstInput - secondInput;
            break;
        case "mul":
            result = firstInput * secondInput;
            break;
        case "divide":
            if (secondInput !== 0) {
                result = firstInput / secondInput;
            } else {
                throw new Error('0으로 나눌 수 없습니다 ^0^');
            }
            break;
    }
    return result;
}
  • 정답 업데이트 함수
function getResult():void {
    const firstInput: number = Number(userInput1.value);
    const secondInput:number = Number(userInput2.value);
    const operator:string = operationType.value;

    const result:number = calculate(firstInput, secondInput, operator);
    answer.innerText = result.toString();
}

resultBtn.addEventListener("click", getResult);

🌮 얼마나:

  • 얼마나 걸렸나요?
    2시간
  • 어떤 부분이 어려웠나요?
  1. main.ts:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "video/mp2t". Strict MIME type checking is enforced for module scripts per HTML spec.
    이 망할 에러가 계속 발생해서 .. 도대체 왜 그런지 ... 계속 구글링 하다가 main.ts를 연결할 때 에러가 발생하는 것이라 컴파일 완료된 main.js파일을 연결하면 에러가 발생하지 않는다는 글을 보고 .. 그렇게 해결했습니다만 아무도 이런 에러가 발생하지 않았나요 ? 여기서만 30분은 쓴 것 같아요 흑흑 ..........

  2. 다음은, 타입스크립트를 활용해서 DOM 요소에 접근하는 방법이 익숙하지 않아서 계속 빨간줄을 마주했습니다 ..
    DOM 요소를 불러올 때도 type을 지정해야 한다는 것을 알았고, HTML element type에 신경써서 구현하느라 오래걸린 것 같습니다 !
    타입을 지정하여 접근해도 null인 경우의 에러까지 발생시켜 주는 친절한 ..^^ 타입스크립트 덕분에 여러 시행착오를 겪었습니당 ,, (덕분에 새롭게 알게 된 부분은 엄청 많네요 )

🌮 구현 사항:

  • 필수 구현 사항이 완료된 부분의 영상을 첨부해주세요
2023-11-08.6.29.16.mov

@se0jinYoon se0jinYoon self-assigned this Nov 8, 2023
@hoeun0723 hoeun0723 linked an issue Nov 13, 2023 that may be closed by this pull request
Copy link
Member

@hae2ni hae2ni left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

서진이 넘 수고했어!!!! 코드 넘 깔꼼티비다!

</main>
<script type="module" src="/src/main.ts"></script>
<script type="module" src="/src/main.js"></script>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

엇 혹시 main.js는 왜 생겼지? 혹시 compile한 건가용,,,??????????
그냥 yarn dev 실행하면 되었을텐디!! 어케된건지 궁금해!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR에 남겨두었는데 !
main.ts:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "video/mp2t". Strict MIME type checking is enforced for module scripts per HTML spec.

이 에러가 계속 떠서 대체 왜 ..... 이런건가 하고 찾아보다가 계속 구글링 하다가 main.ts를 연결할 때 에러가 발생하는 것이라 컴파일 완료된 main.js파일을 연결하면 에러가 발생하지 않는다는 글을 보고 .. 그렇게 해결했습니다만

지금 생각해보니 내가 CRA에 익숙해져 있어서 npm run start로 켰었나 ..? 그래서 저런 에러가 와장창 발생했던 건가란 합리적 의심중 ..

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

호오오옥시 이 파일의 정체가 왜 생겼는지 알 수 있을까? 내가 vite로 만든 ts라서 굳이 컴파일 과정같은게 필요없었을텐디!

const secondInput:number = Number(userInput2.value);
const operator:string = operationType.value;

const result:number = calculate(firstInput, secondInput, operator);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굳굳!!! 하나하나 타입 넣어준 거 너무 죠아요!!

const userInput1: HTMLInputElement = document.getElementById('userInput1') as HTMLInputElement;
const userInput2: HTMLInputElement = document.getElementById('userInput2') as HTMLInputElement;
const operationType: HTMLSelectElement = document.getElementById('operationType') as HTMLSelectElement;
const answer: HTMLElement = document.getElementById('answer')!;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요거 ! 머야! 진짜 많이 생각한게 느껴진다ㅠㅠㅠ 스터디에서 안 다뤘던거 같은데!
! 는 undefined나 null이 될 수 없음을 의미하는 표시라구 생각하시면 됩니다! -> 알고 있겠찌만 ❤️

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

허억 이렇게 연산자로 제한해서 이후에 null값이 들어오는 예외처리를 안해줘도 되겠구나!

answer.innerText = result.toString();
}

function calculate(firstInput:number, secondInput:number, operator:string):number {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요거 인터페이스로 만들면
interface CalculatorInput { firstInput: number; secondInput: number; operator: string; }
그래서 정리하면,

Suggested change
function calculate(firstInput:number, secondInput:number, operator:string):number {
function calculate(firstInput, secondInput, operator): CalculateInput{

result = firstInput * secondInput;
break;
case "divide":
if (secondInput !== 0) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예외처리 굳!

Copy link

@rachel5640 rachel5640 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

섬세한 예외처리와 타입 지정이 너무 인상적입니다🥹
저도 과제하면서 DOM 요소 불러올때에도 타입 지정해줘야하는 걸 보면서,
타스... 정말 까다로운 아이구나..생각했어요ㅎㅎ
금잔디 조하면서도 많이 느꼈지만 언제나 코드가 너무 깔끔해서 많이 배워가요💛

const userInput1: HTMLInputElement = document.getElementById('userInput1') as HTMLInputElement;
const userInput2: HTMLInputElement = document.getElementById('userInput2') as HTMLInputElement;
const operationType: HTMLSelectElement = document.getElementById('operationType') as HTMLSelectElement;
const answer: HTMLElement = document.getElementById('answer')!;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

허억 이렇게 연산자로 제한해서 이후에 null값이 들어오는 예외처리를 안해줘도 되겠구나!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

계산기 프로젝트 구현 내용
3 participants