2강 — 제네릭과 React
2024 DTC
| → / Space | 다음으로 |
| ← | 이전으로 |
| ↓ / ↑ | 같은 주제 안에서 단계 이동 |
| O | 전체 슬라이드 한눈에 보기 |
| F | 전체화면 |
아래쪽 화살표가 보이면 그 주제는 단계별로 이어집니다
| interface | 객체 모양 |
| A | B | 유니온. typeof로 좁힌다 |
| any | 쓰지 않는다 |
오늘은 이걸 React에 붙입니다
타입을 나중에 정하려면
function first(arr: number[]) {
return arr[0];
}
// 문자열 배열에도 쓰려면?
function firstString(arr: string[]) { ... }
타입만 다르고 내용이 같으면 어떻게 할까요?
function first<T>(arr: T[]): T {
return arr[0];
}
first([1, 2, 3]);
first(["a", "b"]);
first([1, 2, 3])numberfirst(["a", "b"])string
interface Box<T> {
value: T;
}
const a: Box<number> = { value: 1 };
const b: Box<string> = { value: "hi" };
Box<number>value: numberBox<string>value: stringArray<T>, Promise<T>useState<T> 도 제네릭이다있는 타입을 변형해서 쓰려면
interface User {
id: number;
name: string;
email: string;
}
Partial<User> // 전부 선택
Pick<User, "id" | "name">
Omit<User, "email">
Required<User>
Partial다 없어도 됨Pick고른 것만Omit뺀 나머지Required다 필수
function update(id: number, data: Partial<User>) {
// name만 바꿔도 되고 email만 바꿔도 된다
}
update(1, { name: "새 이름" });
{ name }통과{ }통과
type Scores = Record<string, number>;
const s: Scores = { 국어: 90, 수학: 85 };
키string값number컴포넌트에 타입을 붙이려면
Profile.tsx
interface Props {
name: string;
age?: number;
}
function Profile({ name, age }: Props) {
return <h1>{name}</h1>;
}
const [count, setCount] = useState(0);
const [user, setUser] =
useState<User | null>(null);
useState(0)number 추론useState<User | null>직접 지정
type E = React.ChangeEvent<HTMLInputElement>;
function onChange(e: E) {
setText(e.target.value);
}
type Props = { children: React.ReactNode };
function Card({ children }: Props) {
return <div>{children}</div>;
}
childrenReact.ReactNode서버에서 받은 값을 쓰려면
const res = await fetch(url);
const data = await res.json();
dataanyres.json()의 타입은 뭘까요?
interface Post {
id: number;
title: string;
}
const data: Post[] = await res.json();
dataPost[]zod 같은 도구로 값까지 검사한다검사 강도를 정하려면
tsconfig.json
{
"compilerOptions": {
"strict": true,
"target": "ES2020"
}
}
strict엄격 검사 묶음target변환할 JS 버전strict: true 로 시작한다JS로 만든 것을 옮기려면
tsconfig.json 추가.js → .ts// @ts-expect-error 로 잠시 미루기strict 켜기.ts 로unknown 으로 두고 넘어간다TypeScript 2강 전체
| 1강 | 기본 타입, 함수, interface, 유니온 |
| 제네릭 | 타입을 인자처럼 받는다 |
| Partial Pick Omit | 있는 타입을 변형 |
| React | props는 interface, useState<T> |
| 외부 데이터 | 타입은 약속일 뿐 검사가 아니다 |
| strict | 처음부터 켜둔다 |
직접 해봅시다
.tsx 로 옮기기interface Todo 를 만들고 props에 붙이기any 가 하나도 없게 만들기수고하셨습니다