타입스크립트 교과서 2.1~2.8 정리

이수빈·2023년 9월 13일
1

Typescript

목록 보기
1/17
post-thumbnail
  • Typescript 교과서라는 책을 읽고 공부한 내용을 블로그에 정리하고자 한다.

타입정의, 타입추론

  • 변수, 매개변수, 반환값에 콜론을 사용해 type 정의

  • 타입스크립트는 변수와 반환값의 타입을 스스로 추론 할 수 있다.

  • 단 함수의 매개변수는 type을 정의해야한다. 어떤값이 들어올 지 모르기 때문이다.

  • 타입스크립트가 타입을 제대로 추론하면 그대로 쓰고, 틀리게 출론하면 올바른 타입을 표기한다.

const minusFunction1 = (x:number, y:number) : number => x-y;
// 함수 매개변수, return에 직접정의
// return을 정의하지 않아도 오류발생하지 않음.  

type minusFuntion = (x:number, y:number) => string;

const minusFunction2:minusFuntion= (x,y) => x-y; 

// 함수의 type을 따로 정의 
// return값을 세세하게 제어해야할때 => type을 정의해주는게 좋음.

리터럴타입

  • 타입을 표기할 때 "hello", 123, false와 같이 정확한 값을 입력하는 것.

  • 타입을 표기할때는 더 넓은 타입으로 표기해도 문제가 없다.

  • null, undefined를 let 변수에 대입할때는 any로 추론함.

const str = "hello"; // str:"hello" type으로 추론
const str2 :string = "hello" // str2 : string type으로 명시함 (문제발생 x)
let str3 = "hello" // str3 : string type으로 추론

as const 키워드

  • as const 사용해서 이를 방지가능 ( const로 선언된 객체라도 참조해서 내부값 변경 가능함)

  • 정말 상수처럼 사용해야하는 객체에 사용하면 좋을 듯 (값이 변하지 않는 객체)


const arr1 =[1,2, "vife"]; // string | number []
  
const arr =[1,2, "vife"] as const; // readonly [1,2,"vife"] 

배열, 튜플 Type

  • 튜플이란 ? => 각 요소 자리에 타입이 고정되어 있는 배열임.

  • 표기하지 않은 index => undefined type으로 됨.

  • 튜플을 사용하면 아래와 같은 문제가 발생하는 것을 막을 수 있다.

  • 정의되지 않은 인덱스에 접근하는 것은 막지만, push, pop, unshift, shift 메서드를 통해 값을 추가하고 제거하는 것은 가능함. => 이를 방지하려면 readonly를 붙혀야함.

const tuple : [number, boolean, string] = [1, false, 'hi'];

const array = [12,23,4123] //number[]
array[3].toFixed() 
// number형으로 추론 하지만 실제값은 undefined임.

const strNumBools : [string, number, ...boolean[] ] 
// spread operator 사용가능. 

const [a, ...rest1] = ["hi" ,1,2,3,442] 
// a : string
// rest1 : [number,number,number,number]
  • 마지막에서 rest1 자체를 TS는 튜플로 추정한다. number[] 가 아님.

값을 타입으로 사용하기

  • 변수에 typeof 연산자 사용하면 type으로 추출가능하다. (typeof 연산자에는 함수 반환값은 올수 없다)

  • Wrapper 객체보단 원시타입으로 타입정의하는것을 권장함.

const add = (x:number, y:number) => x+y;

type addType = typeof add

const add2:addType = (x,y) => x+y;

type returnType = typeof add2(1,2); //에러

Union Type & Any

  • 여러개의 타입을 가질 가능성을 표시, | 연산자로 표현함

  • 만약 여러개의 타입을 가지는 변수를 처리할 때 => 타입가드를 통해 특정 타입 case마다 handling 해줘야함.

  • any 핸들링 : any타입은 타입검사를 포기한다는 선언과 같다 => any로 추론하는 타입이 있따면 타입을 직접 표기해야한다.

  • typescript가 명시적으로 any를 반환하는 경우도 존재함. => 직접 타이핑하여 향후 모든 type이 any가 되는 것을 방지해야함.

ex) fetch, JSON.parse, axios는 따로 type이 존재하는 듯?

// 예시: Promise를 반환하는 비동기 함수 using fetch
async function fetchData<T>(url: string): Promise<T> {
  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data: T = await response.json();
    return data;
  } catch (error) {
    throw new Error(`Error: ${error}`);
  }
}

// 사용 예제
fetchData<{ name: string, age: number }>('https://api.example.com/user/1')
  .then(user => {
    console.log(user.name); // user 객체에 접근 가능
  })
  .catch(error => {
    console.error(error);
  });
//예시: Promise를 반환하는 비동기 함수 using axios
import axios, { AxiosResponse } from 'axios';

// 서버 응답 데이터를 나타내는 타입을 정의
interface ApiResponse {
  id: number;
  name: string;
  // 다른 필드들을 여기에 추가
}

// 서버로부터 데이터를 가져오는 비동기 함수
async function fetchData<T>(url: string): Promise<T> {
  try {
    const response: AxiosResponse<T> = await axios.get(url);

    // 서버 응답이 성공적인지 확인
    if (response.status !== 200) {
      throw new Error('서버 응답이 실패했습니다.');
    }

    // 응답 데이터를 반환
    return response.data;
  } catch (error) {
    throw new Error(`데이터를 불러오는 중 오류가 발생했습니다: ${error.message}`);
  }
}

// 사용 예제
async function main() {
  try {
    const apiResponse: ApiResponse = await fetchData<ApiResponse>('https://api.example.com/data');
    console.log(apiResponse.id, apiResponse.name);
  } catch (error) {
    console.error(error.message);
  }
}

main();

다른 type들

unknown

  • try..catch문에서만남 이후 어떤 동작도 수행불가.

  • 타입 강제변환 : as 연산자 or <>사용

    as unknown으로 변환 후 다시 원하는 타입으로 변환 가능
    as로 강제변환하는 것을 권장함

const abc:number = '123' as unknown as number
const error = e as Error
const error = <Error>e; //강제변환 2가지방법, 
  • non-null assertion 연산자 : null, undefined가 아님을 주장하는 연산자임(밑에 타입가드랑 같은코드)
function test(param:string|null|undefined){
    param!.slice(1);
}

function test(param:string|null|undefined){
    if(param === null || param === undefined){
        return;
    }
    param.slice(1);
}

void의 사용

  • 사용자가 함수의 반환값을 사용하지 못하도록 제한한다.
  • 반환값을 사용하지 않는 콜백함수를 타이핑할때 사용한다.
  • 콜백함수는 여러형태로 사용가능하기 때문에 미리 어떤값이 들어오는지 알 수 없어서 void형태로 표시

{}, Object

  • null, undefined를 제외한 모든 값을 의미함.

  • 실제로 대입하는것은 의미가 없음

never

  • never 타입은 어떠한 값도 대입 할 수 없다.

Type Alias

  • type키워드를 이용한 복잡한 type 선언, 대문자로 선언하는 것이 관습임

  • 가독성이 떨어지는 곳 (함수, 객체 ... 등에 사용함)

profile
응애 나 애기 개발자

0개의 댓글