TypeScript 배워보기

LeeJaeHoon·2021년 12월 6일
0
post-thumbnail
  1. 타입
    • number
      • const n: number = 1
    • string
      • const name: string = "jaehon"
    • boolean
      • const result: boolean = true
    • object
      const person: {name: string, age: number} = {
        name: "leejaehoon",
        age: 30,
      };
    • Array
      • const ary: string[ ] = [ "a", "b" ]
        • array의 item으로 string만 가능
    • tuple
      • const role: [ string, number ]
        • 0번째 인덱스엔 string이 1번째 인덱스엔 number이 와야한다.
        • role[1] = "a" → 오류 (1번째 인덱스엔 number이 와야한다.)
    • enum
      enum job { AUTHOR, STUDENT}
      console.log(job.AUTHOR); //0 
      
      enum job { AUTHOR = 1 , STUDENT}
      console.log(job.AUTHOR); //1
      console.log(job.STUDENT); //2
      
      enum job { AUTHOR = "good" , STUDENT}
      console.log(job.AUTHOR); //good
    • union type
      const combine = (
        input1: number | string | boolean,
        input2: number | string
      ) => {
        let result;
        if (typeof input1 === "number" && typeof input2 === "number") {
          result = input1 + input2;
        } else {
          result = input1.toString() + input2.toString();
        }
        return result;
      };
      
      const a = combine("Max", "Anna");
      console.log(a);
    • 리터럴 타입
      const a: "good" | "bed";
      a = "good" //work!
      a = "v" //error
    • 타입 알리어스
      type Combine = number | string 
      const a: Combin;
      a = "good" //work!
      a = true // error
      • 복잡할 수 있는 객체 타입에도 별칭을 붙일 수 있습니다.

        type User = { name: string, age: number };
        const u1: User = { name: "jaeHoon", age : 22 }; // work!
        const u1: User = { name: "jaeHoon", age : 22 , local: "busan"}; //error 
    • 함수 반환 타입
      const add = (n1: number, n2: number): number {
      	return n1 + n2
      }
    • 타입의 기능을 하는 함수
      const add = (n1: number, n2: number): number {
      	return n1 + n2
      }
      const combine = (n1: number) => {
      	console.log(`n1: ${n1}`);
      }
      
      // 첫번째 argument가 number이고 두번째 argument가 number이고 return값이 number인
      // 함수를 타입으로 한다는 뜻.
      let combineValue: (a: number, b: number) => number;
      combineValue = add // lt's work! 
      combineValue = combine // error
    • 함수 타입과 콜백
      • 콜백 함수는 자신이 전달되는 인수가 반환 값을 기대하지 않는 경우에도 값을 반환할 수 있습니다.

        function sendRequest(data: string, cb: (response: any) => void) {
          // ... sending a request with "data"
          return cb({data: 'Hi there!'}); 
        }
         
        sendRequest('Send this!', (response) => {  //lt's work!
          console.log(response);
          return true;
         });
    • unKnown type
      let userInput: unknown; //사용자가 어떤 값을 넣을지모름
      let userName: string;
      
      userInput = 5; //lt's work!
      userInput = "max"; //lt's work!
      userName = userInput //error 
      
      if (typeof userInput === "string") {
      	userName = userInput //lt's work!
      }

0개의 댓글