본문 바로가기
today,weekly I learn

24.6.25

by rhdaud2 2024. 6. 25.

 

 

 

 

 

 

 

 

 

built-in type (내장 타입)

 

number

string

boolean

object

 - array

 - function

void

undefined

any

null

 

 

type alias(타입 별칭) interface

 

//type / interface

type Example = string;

type Example = {
	name : string;
    age: number;
}

interface Example {
	name: string;
    age: number;
    음료: "콜라" | "사이다";
}

 

type alias(타입 별칭) / interface  차이점

 

interface : 객체 형태로 선언, 중복 선언 가능

 

 

 

타입 추론 : 타입을 명시적으로 지정하지 않아도, 코드의 문맥으로 타입을 추론한다

 

 

타입 어노테이션 : 콜론과 함께 타입 명시

 

 

 

*구조적 타입

구조가 동일하면 같은 타입으로 본다

 

 

*제네릭 : 타입을 파라미터처럼 사용하는 것 - 타입을 변수로 사용하고싶을 때 / 사용자가 입력해서 쓰고 싶을 때 사용

function sum(a:number, b:number):number{
	return a + b
}

type Generic<T> = {
	name: T,
}
type Example = Generic<string>

 

 

 

 

 

 

 

 

 

 

 

 

* 비동기 함수에서 ts 사용

 

type Person = { id: number; age: number; height: number };

async function getPerson(): Promise<Person[]> {
  const res = await fetch(`http://localhost:5008/people`);
  if (!res.ok) {
    throw new Error();
  }
  return res.json();
}

getPerson().then((res) => console.log(res[0]));

 

 

 

제네릭(generic): 데이터 타입 일반화(generalize) = > 타입 변수화

// 제네릭(generic)이란 데이터의 타입(data type)을 일반화한다(generalize)는 것을 의미합니다.
type Generic<T> = {
  someValue: T;
};

type Test = Generic<string>;

function someFunc<T>(value: T) {}

someFunc<string>("hello");

 

 

*useState 에서의 사용

import { useState } from "react";

function App() {
  const [counter, setCounter] = useState<number>(1);
  const increment = () => {
    setCounter((prev) => prev++);
  };
  return <div onClick={increment}>{counter}</div>;
}

export default App;

 

 

*props 넘기기

import { useState } from "react";

function Parent() {
  const [count, setCount] = useState("");
  return <Child count={count}></Child>;
}

type Props = {
  count: string;
};

function Child({ count }: Props) {
  return <div>{count}</div>;
}

export default Parent;

 

 

 

 

 

 

☑️ enum을 쓰면 좋은 경우

  • enum은 간단한 상수 값을 그룹화해서 관리를 할 때 적합해요!
  • 또한, enum은 상수 값이기 때문에 각 멤버의 값이 변하면 안된다는 조건이 있어요.

☑️ 객체 리터럴을 쓰면 좋은 경우

  • 객체 리터럴은 멤버의 값이나 데이터 타입을 맘대로 변경할 수 있어요!
  • 복잡한 구조와 다양한 데이터 타입을 사용해야 할 때는 객체 리터럴을 사용하세요!

 

 

 

'today,weekly I learn' 카테고리의 다른 글

24.6.27  (0) 2024.06.27
24.6.26  (0) 2024.06.26
24.6.20 - update post  (0) 2024.06.20
24.6.19-댓글 기능(supabase,tanstack-query)  (0) 2024.06.19
24.6.18-form tag, button type  (0) 2024.06.18