-
24.06.27 TILsparta TIL 2024. 6. 27. 04:45
베이직분반
TypeScript
∙ 함수에 타입 지정
function 인사하기(이름: string, 나이: number): string { return `안녕 내 이름은 ${이름}이고, 나이는 ${나이}살이야`; } function 인사하기2({ 이름, 나이 }: { 이름: string; 나이: number }): string { return `안녕 내 이름은 ${이름}이고, 나이는 ${나이}살이야`; } console.log(인사하기("병수", 12)); console.log(인사하기2({ 이름: "병수", 나이: 12 }));
∙ 비동기 함수에서 return 타입 지정 ( 리턴부분 : Promise<타입> )
interface todo { userId: number; id: number; title: string; completed: boolean; } async function 데이터가져오기(): Promise<todo> { const response = await fetch("https://jsonplaceholder.typicode.com/todos/1"); const result = await response.json(); // result === { // "userId": 1, // "id": 1, // "title": "delectus aut autem", // "completed": false // } return result; }
∙ useState 에서 타입 지정
import { useState } from "react"; function App() { const [counter, setCounter] = useState<number>(1); const increment = () => { setCounter((prev) => { return prev + 1; }); }; return ( <> <div>{counter}</div> <button onClick={increment}>증가</button> </> ); } export default App;
∙ props에서 타입 지정 ( type 또는 interface )
import { useState } from "react"; function ParentComp() { const [count, setCount] = useState(0); return <ChildComp count={count}></ChildComp>; } type Props = { count: number; }; function ChildComp({ count }: Props) { return <div>{count}</div>; } export default ParentComp;
import { useState } from "react"; type Todo = { id: string; title: string; }; function App() { const [todos, setTodos] = useState<Todo[]>([ { id: "1", title: "잠자기", }, { id: "2", title: "늦게까지 놀기", }, ]); const deleteTodo = (id: string) => { const newTodos = todos.filter((todo) => todo.id !== id); setTodos(newTodos); }; return ( <> {todos.map(({ id, title }) => ( <Todo key={id} id={id} title={title} deleteTodo={deleteTodo} /> ))} </> ); } function Todo({ id, title, deleteTodo, }: { id: string; title: string; deleteTodo: (id: string) => void; }) { const handleOnClick = () => { deleteTodo(id); }; return ( <> <div> {id}: {title} <button onClick={handleOnClick}>삭제</button> </div> </> ); } export default App;
∙ Event Handler타입 지정 ( onChange, onClick 속성에서 힌트 ! )
import { useState } from "react"; function App() { const [counter, setCounter] = useState<number>(1); const eventHandler = (e: React.MouseEvent<HTMLDivElement>) => {}; return <div onClick={eventHandler}>{counter}</div>; } export default App;
import { useState } from "react"; function App() { const [counter, setCounter] = useState<number>(1); const eventHandler = (e: React.ChangeEvent<HTMLInputElement>) => {}; return <input onChange={eventHandler}>{counter}</input>; } export default App;
∙ type 과 interface 로 객체 타입 지정하기
1. interface 작성
interface ButtonProps { label: string; onClick: () => void; }
2. type 작성
type ButtonProps = { label: string; onClick: () => void; }
interface, type 차이가 무엇 ?
- type 은 유연한 타입 정의 가능 ( 객체 뿐 아니라 다양한 타입 가능 )
// 객체 타입 type Data = { a: string; b: number; } const data: Data = { a: "10", b: 20 }; // 유니언 타입 type C = number | string | boolean; const c1: C = 123; const c2: C = "123"; const c3: C = true;
- type 은 확장(extends)가 불가하고, interface 는 가능함
// interface 확장 예시 interface ButtonProps { children: React.ReactNode; onClick: () => void; } interface BeautifulButton extends ButtonProps { backgroundColor: "red" | "blue" | "green"; } function Button({ children, onClick, backgroundColor, }: BeautifulButton) { return <button onClick={onClick} style={{ backgroundColor }}>{children}</button>; } export default function App() { return ( <div> <Button onClick={() => { }} backgroundColor="red">버튼</Button> </div> ); }
// type 확장 예시 (억지로 확장하기) type ButtonProps = { children: React.ReactNode; onClick: () => void; } type BeautifulButton = ButtonProps & { backgroundColor: "red" | "blue" | "green"; } function Button({ children, onClick, backgroundColor, }: BeautifulButton) { return <button onClick={onClick} style={{ backgroundColor }}>{children}</button>; } export default function App() { return ( <div> <Button onClick={() => { }} backgroundColor="red">버튼</Button> </div> ); }
generic
- 함수에 유동적인 값을 받으려면? parameter 를 이용한다.
// 파라미터가 없다면? function 일더하기일함수() { return 1 + 1; } function 일더하기이함수() { return 1 + 2; } function 일더하기삼함수() { return 1 + 3; } // 파라미터를 활용한다면? function 일더하기몇함수(num) { return 1 + num; }
- 타입에 유동적인 타입을 지정하려면? ⇒ generic 을 이용한다.
- 함수 이름 옆에 <알파벳>
- 파라미터에 : 알파벳
- 리턴 타입에 필요하면 : 알파벳
function identity<T>(arg: T): T { return arg; } // 사용 예시: let output = identity<string>("myString"); let output2 = identity<number>(12) let output3 = identity<boolean>(false)
function pair<T, U>(first: T, second: U): [T, U] { return [first, second]; } const result = pair<string, number>("hello", 42);
- 타입 옆에 <알파벳>
- 객체 속성에 : 알파벳
type SimpleObject<T> = { value: T; }; // 사용 예시: let object: SimpleObject<number> = { value: 10 }; // object는 { value: 10 }입니다. let anotherObject: SimpleObject<string> = { value: "hello" }; // anotherObject는 { value: "hello" }입니다.
'sparta TIL' 카테고리의 다른 글
NEXT.js 과제 (0) 2024.07.02 24.07. NEXT.js TIL (0) 2024.07.02 TypeScript 과제 (0) 2024.06.26 TypeScript Til 2 (0) 2024.06.25 TypeScript TIL 1 (0) 2024.06.25