typescript (1)

BirdsOnTree·2022년 12월 20일
0

typescript

목록 보기
1/3
post-thumbnail

기본

const hangle: string = "한글";

object

const required: { name: string; age: number } = { name: "nkh", age: 999 };

// 타입 단언(as)의 속성을 이용하면 인터페이스 정의 시점에서 object를 채워주지 않아도 에러가 도출 되지 않는다.
const required = {} as { name: string; age: number };

// 꼭 없어도 되는 속성 하지만 있다면 타입을 맞춰야함, ?를 붙인다.
const selection: { name: string; age?: number } = { name: "nkh" };

// 읽기만 가능하고 재할당 금지
const readOnly: {readOnly name: string} = {name: "nkh"}

array

// string만 받는 배열
const onlyString: string[] = ["a", "b"];

// number만 받는 배열
const onlyNumber: number[] = [1, 2];

// 제네릭
const onlyString: Array<string> = ["a", "b"];

// 제네릭
const onlyNumber: Array<number> = [1, 2];

const arr: [string, number] = ["string", 10]; 
// 0번째에는 string만 들어갈수 있고, 1번째 배열에는 number만 들어갈수 있다.

Enum

상수의 집합입니다. html의 option 태그 같이 어떠한 종류에 대한 지정된 타입이 들어오는 경우 틀린 상수 값이 들어오는 것을 막기 위해 Enum으로 상수의 집합을 만들고, 그 이외의 값은 받지 않는다.

enum PhoneType {
  Home = "home",
  Office = "office",
  Studio = "studio"
}
const str: PhoneType = PhoneType.Home; //home

void

// 변수에는 undefined, null만 할당이 가능하다.
const unuseData: void = undefined;

// 함수에는 return 값이 없을 때, 설정하는 타입이다.
function notReturnValue(): void {
  console.log(1);
}

never

해당 함수의 맨 마지막까지 도달하지 않는다는 타입 절대로 발생하지 않는 값으로 에러 핸들링 함수에서 사용한다.
주로 함수의 리턴 타입으로 에러가 발생할 경우 에러를 무시하고 계속 진행시키는 역할한다. 또는 대체 불가한 값을 만들 때 사용한다. 재할당 불가

// 이 함수는 절대 함수의 끝까지 실행되지 않는다는 의미
function neverEnd(): never {
  while (true) {
    ...
  }
  // 여기는 도달하지 않아요
}

function errorThrow(): never {
  //에러 발생한 경우 중지하지 않고 throw 함수 실행
  throw new Error("error");
}

union

여러 타입을 지정하고 싶은 경우 | 를 사용한다.

let value: string | number = "foo";

union 인터셉션

| 는 또는 이라면 & 는 and 입니다.

interface Test {
  name: string;
  skill: string;
}
interface Test2 {
  name: string;
  age: string;
}

function ask(someone: Test | Test2) {
  console.log(someone.name); // interface의 공통 속성으로 접근 가능
  // someone.skill, age는 공통속성이 아니므로 접근 불가능

  // 접근하고 싶다면 타입 가드로, 하나의 타입만 필터링 한 경우만 활용 가능
}

// &를 이용하면 3개의 속성 활용 가능 (인터섹션)
function ask(someone: Test & Test2) {
  // Test와 Test2 두개의 interface를 포함하게 타입 정의
  console.log(someone.name);
  console.log(someone.skill);
  console.log(someone.age);
}

| 를 쓰면 함수 호출시 두개의 인터페이스 중 1개만 보장해주면 되나, &를 쓰면 함수 호출시 두개의 인터페이스 타입을 다 보장해줘야하므로 | 를 좀 더 많이 쓴다.

axios response call interface

  • 다음은 api를 받을때 response 값 타입을 정의하는 방법입니다.
  • api는 promise로 받으니 Promise로 감싸주고 그 안에 AxiosResponse를 사용합니다.
  • 그 안에 이미 정의한 interface를 가져와 완성합니다.
import axios, { AxiosResponse } from "axios";

interface CovidSummaryResponse {
  Countries: any[];
  // {Country: "Afghanistan", CountryCode: "AF", Slug: "afghanistan", NewConfirmed: 241}
  Date: string;
  Global: any;
  Message: string;
}

// api axios response 정의
function fetchCovidSummary(): Promise<AxiosResponse<CovidSummaryResponse>> {
  const url = "https://api.covid19api.com/summary";

  return axios.get(url);
}

// 위 response interface 정의로 타입 추론
fetchCovidSummary().then(res => res.data.Message);

출처:
[기억보다 기록을]
https://kyounghwan01.github.io/blog/TS/fundamentals/basic/#boolean

0개의 댓글