[TS] 타입 주석과 추론

단비·2023년 3월 3일
0

인강

목록 보기
2/15
  • TypeScript는 node(js)를 거친후 돌아감
  • NodeJs는 자바스크립트 런타임

  1. npm init
    • package.json 파일이 만들어짐
  2. tsc --init
    • tsconfig.json 파일이 만들어짐
  • tsconfig.json
    • include: 어떤 파일을 컴파일 할것인지

    • exclude: 어떤 파일을 컴파일 제외 시킬 것인지

      "include": ["**/*.ts"], // 모든 폴더의 모든 ts파일을 컴파일 시킴
      "exclude": ["node_modules"]
  • ts 파일을 만든 후 컴파일시킨 후 노드 확인 시
    1. tsc ano.ts → node ano.js
    2. tsc ano.ts && node ano.js
    3. tsc && node ano.js
      • tsc만 써도 모든 파일 컴파일이 가능한 이유는 위에서 include 를 따로 설정해줬기 때문

  • 타입 주석과 추론
    1. any

      • 전부 삽입 가능. 사용 잘 안함
    2. number

      • 숫자형만 삽입 가능 - int, Long
    3. string

      • 문자열만 삽입 가능 - “”, ‘’, ``
    4. boolean

      • true, false만 삽입 가능
    5. object
      - 객체({})계의 any. 사용 잘 안함

      const a: number = 1;
      // 오류: const a: number = "hello";
      const b: string = 'hi ts';
      const c: boolean = true;
  • 타입 추론
    • 처음 선언 시 number로 설정되었기 때문에 string 으로 들어갈 수 없음

      let d = 1;
      // 오류: d = 'hi'

  • 인터페이스
    1. 인터페이스 선언

      // 명세, 타입, 클래스를 만들 때
      interface IPerson {
          name: string;
          age: number;
          city?: string; // city라는 값을 받을지 안받을지 모를 경우
      }
      
      const woman: IPerson = {
          name: 'danbi',
          age: 25,
          city: "seoul"
      }
    2. 따로 선언하지 않고 타입을 지정해줄 때

      const woman: {name: string; age: number; city?: string} = {
          name: 'danbi',
          age: 25,
          city: "seoul"
      }
    3. 함수에 지정해줄 때

      function prt(params: IPerson){
          console.log(params?.city ?? "defalut city");
      }
      prt(woman)

  • 배열의 타입 설정
const arr1: number[] = [1, 2, 3] // 주로 사용
const arr2: Array<number> = [1, 2, 3]

const arr3: string[] = ['hi', 'hello', 'world'];
const arr4: Array<string> = ['hi', 'hello', 'world'];
  • 배열 안에 객체들이 있는 경우 타입 설정
interface IPerson {
    name: string;
    age: number;
    city?: string;
}

const arr5: IPerson[] = [
    {
        name: 'danbi',
        age: 25,
        city: "seoul"
    },
    {
        name: 'danbi',
        age: 25,
    },
		...
]
arr5.forEach((e: IPerson) => console.log(e?.city ?? "default"));
  • 튜플의 타입 설정
    • 튜플 - 배열의 길이 length와 안의 원소를 바꿀 수 없음(불변성 유지)

      const arr6: [number, string, object, any[]] = [1, 'hi', {}, []];
profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글