반응형
Notice
Recent Posts
Recent Comments
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Archives
Today
Total
관리 메뉴

UP

Typescript : 타입 추론(Type Inference) 본문

TypeScript

Typescript : 타입 추론(Type Inference)

cijbest 2021. 5. 27. 11:57

타입 추론(Type Inference)

타입스크립트는 타입 표기가 없는 경우 코드를 읽고 분석하여 타입을 유추


Static Typing(정적 타이핑)

  • 타입을 선언하고 타입에 맞는 값만이 할당 or 반환되어야 한다.

타입 추론 예시 1

  • app.ts

    let a = 5;
    a = 'hello';

    에러 발생!

    app.ts:2:1 - error TS2322: Type 'string' is not assignable to type 'number'.
    
    2 a = 'hello';
      ~

    변수 a가 이미 숫자타입으로 선언되어 있기 때문에 문자타입으로 재선언하는 것은 불가능

    같은 타입으로는 선언 가능 ex) a = 10


타입 추론 예시 2

  • app.ts

    let student = {
        name: 'Jake',
        course: 'Gettin Started with TypeScript',
        codingIQ: 80,
        code: function(){
            console.log('brain is working hard');
        }
    }
    student.name = 10;

    student.name에 빨간 밑줄이 그어진다!

    이미 name이라는 변수는 타입이 string으로 명시가 되었기 때문에 number로 재선언 될 수 없다.

    예시2


타입 추론 예시 3

  • app.ts

    function claculateCodingIQ(lostPoints){
        return 100 - lostPoints;
    }

    lostPoints에 타입을 명시하지 않았지만 타입스크립트는 return의 반환값을 통해 number 타입임을 유추한다.

    예시3




실습 코드 : https://github.com/cijbest/TIL/tree/master/TypeScript/%EC%8B%A4%EC%8A%B5/Day_2

공부 영상 출처 : [땅콩코딩] https://youtu.be/rwqqhvR353A

반응형
Comments