2. TypeScript
ํ์ต ํค์๋
REPL
TypeScript
Interface vs Type
ํ์ ์ถ๋ก
Union Type vs Intersection Type
Optional Parameter
REPL
REPL(์ฝ์ ํ๊ฒฝ)์ ์ฐ๊ณ ์ถ๋ค๋ฉด ts-node๋ฅผ ์คํํ๋ฉด ๋๋ค.
npx ts-node
ts-node๋ node_modules์ ์ค์น๋์ด ์์ง ์์ผ๋ฏ๋ก ๋ฐ๋ก ์ค์น๋ฅผ ํด์ฃผ์ด์ผ ํ๋ค.
ํ์
์คํธ๋ฆฝํธ์ ํ์
๊ธฐ๋ณธ์ ์ธ ํ์
์๋ฐ์คํฌ๋ฆฝํธ๋ฅผ ์ด์ฉํ ๋๋ typeof ์ฐ์ฐ์๋ฅผ ์ด์ฉํด์ ํ์ ์ ์ถ๋ก ํ๊ณค ํ์๋ค.
๋ํ์ ์ผ๋ก string
, number
, boolean
๋ฑ์ด ์๋ค.
๋ฐฐ์ด
๊ทธ๋ ๋ค๋ฉด ๋ฐฐ์ด์ ํ์ ์ ์ด๋ป๊ฒ ์ง์ ํ ๊น?
์๋ฅผ ๋ค์ด [1, 2, 3]
๊ณผ ๊ฐ์ด ์ซ์๋ก๋ง ์ด๋ฃจ์ด์ง ๋ฐฐ์ด์ด๋ฉด number[]
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ค.
any ํ์
ํ์ ๊ฒ์ฌ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ ๊ฒ์ ์ํ์ง ์์ ๋ ์ฌ์ฉํ ์ ์๋ค. ๊ทธ๋ฌ๋ฏ๋ก ์๋ฌด ํ์ ์ด๋ ๋ค ๋ค์ด์ฌ ์ ์๋ค.
ํ์
์ง์
๋ณ์/๊ฐ์ฒด
let name: string;
let age: number;
name = "ํ๊ธธ๋";
age = "13";
let human: {
name: string;
age: number;
};
human = { name: "ํ๊ธธ๋", age: 13 };
์ผ๋ฐ ๋ณ์๋ ๊ฐ์ฒด ๋ด๋ถ๊น์ง type์ ์ ์ํ ์ ์๋ค. type ๋ณ์นญ์ด๋ interface๋ฅผ ์ฌ์ฉํ์ฌ ๊ณ์ ์ฌ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
๋ฐฐ์ด ํ์
์ง์
let numbers: number[];
numbers = [1, 2, 3];
๊ธฐ๋ณธ์ ์ผ๋ก๋ ์์ฒ๋ผ ์ฌ์ฉํ๋ฉด ๋์ง๋ง ์กฐ๊ธ ๋ ์๊ฒฉํ๊ฒ ํ์ ์ ๊ด๋ฆฌํ๊ณ ์ถ๋ค๋ฉด Tuple์ ์ด๋ค. ๋ฐฐ์ด ๊ฐ์์ ํ์ ๊น์ง ์ง์ ํ ์ ์๋ค.
let anythings: any[];
let anythings: ["hp", 256];
let pair: [string, number];
pair = ["hp", 256];
์ธํฐํ์ด์ค ํ์ฅํ๊ธฐ
interface Animal {
name: string;
}
interface Bear extends Animal {
honey: boolean;
}
const bear = getBear();
bear.name;
bear.honey;
๊ต์งํฉ์ ํตํ์ฌ ํ์
ํ์ฅํ๊ธฐ
type Animal = {
name: string;
};
type Bear = Animal & {
honey: Boolean;
};
const bear = getBear();
bear.name;
bear.honey;
ํจ์ ํ์
์ง์
ํจ์ ๋ฐํ๊ฐ๊ณผ ์ธ์์๋ ํ์ ์ง์ ์ด ๊ฐ๋ฅํ๋ค.
function getMutiply(x: number, y: number): number {
return x * y;
}
์ ๋์จ ํ์
let y: true | false;
y = true;
y = false;
์ ๋์จ ํ์ ์ ์ด์ฉํ๋ฉด ์๋ก ๋ค๋ฅธ ๋๊ฐ ์ด์์ ํ์ ๋ค์ ์ฌ์ฉํ ์ ์๋ค. ์๋์ ๊ฐ์ด ์ ์ฉํ๊ฒ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค. ์ฃผ๋ก ํจ์์์ ๋ง์ด ์ฌ์ฉํ๋ค.
type Category = "food" | "toy" | "bag";
let c: Category;
c = "toy";
c = "bread"; // error
function fetchProducts({ category }: { category: Category }) {
console.log(`Fetch ${category}`);
}
fetchProducts({ category: "food" }); // Fetch food
fetchProducts({ category: "bread" }); // error
์ต์
๋ ์ฐ์ฐ์
๊ธฐ๋ณธ์ ์ผ๋ก ํจ์์ ์ธ์ ๊ฐ์ด ์๋ค์ด์ค๋ฉด undefined๋ก ์ค์ ํ๊ณ ์ถ์ ๋ ์ฌ์ฉํ๋ค.
function add(x: number, y?: number): number {
return x + (y || 0);
}
์ธ์ ๊ฐ์ด ์๋ค์ด์์ ๋ ๋์์ผ๋ก ๋ ์ข์ ๋ฐฉ๋ฒ์ผ๋ก๋ ์ธ์์ ๊ธฐ๋ณธ๊ฐ์ ์ค์ ํ๋ ๊ฒ์ด๋ค.
function add(x: number, y: number = 0): number {
return x + y;
}
function greeting(name?: string): string {
return `Hello, ${name || "world"}`;
}
Optional Parameter๋ ๋งค๊ฐ๋ณ์๊ฐ ๊ฐ์ฒด์ผ ๋ ์์ฃผ ํ์ฉ๋๋ค. (๋์ด๊ฐ ์์์๋ ์๊ณ ์์์๋ ์๊ธฐ ๋๋ฌธ)
function greeting({ name, age }: { name: string; age?: number }): string {
return age ? `${name} (${age})` : name;
}
์ฝ๋ ์์
//App.tsx
export function App({ name }: { name?: string }) {
return <p>Hello, {name || "world"}!</p>;
}
//main.tsx
import ReactDOM from "react-dom/client";
import { App } from "./App";
const element = document.getElementById("root");
if (element) {
const root = ReactDOM.createRoot(element);
root.render(<App name="minhye" />);
}
Last updated