โจ Record<K, T>
K๋ key, T๋ value๋ผ๊ณ ๋ณด๋ฉด ๋๋ค.
๊ทธ๋์ Record๋ ์ฌ์ค์ key์ value์ ํ์ ์ ์ง์ ํ๋ค.
type User = Record<string, number>;
const userAge: User = {
Alice: 25,
Bob: 30,
Charlie: 22,
};
์์๋ฅผ ๋ณด๋ฉด ๋ฐ๋ก ์ดํดํ๊ธฐ ์ฌ์ด๋ฐ ์ฌ๊ธฐ์ key๋ String, ๊ฐ์ Number๋ง ๊ฐ๋ฅํ๋ค.
type StatusCodes = Record<"success" | "error" | "loading", string>;
const status: StatusCodes = {
success: "Operation was successful",
error: "There was an error",
loading: "Loading...",
};
์ด๋ ๊ฒ ๋ ๊ตฌ์ฒด์ ์ผ๋ก key๋ฅผ ์ ์ํ ์๋ ์๋๋ฐ,
key์๋ "success", "error", "loading"๋ง ๋ค์ด๊ฐ ์ ์๋๋ก ๊ณ ์ ๋์ด ์๊ณ
value๋ string๋ง ๋ค์ด๊ฐ ์ ์๋ค.
type Item = Record<"id" | "name" | "price", string | number>;
const product: Item = {
id: 101,
name: "Laptop",
price: 1200,
};
์ฌ๊ธฐ ์ข ๋ ๋ณต์กํ ์์๊ฐ ์๋๋ฐ key์๋ id,name,price๋ง ๋ค์ด๊ฐ ์ ์๊ณ value๋ String์ด๋ Number๊ฐ ๋ค์ด๊ฐ ์ ์๋ค.
๐ Record๋ ์ด๋ ๊ฒ ์ ํด์ง ํค์ ๋ํด ์ผ๊ด๋ ๊ฐ์ ๊ฐ์ง๋๋ก ํ์ ์ ์ ์ํ ๋ ์ ์ฉํ๋ค.
์ ๊ทธ๋ฌ๋ฉด Interface๋์ ์ด๋ป๊ฒ ๋ค๋ฅผ๊น ? ๐ค
โจ interface
interface๋ ๊ฐ์ฒด์ ํฌํจ๋ ์์ฑ์ ์ด๋ฆ๊ณผ ํ์ ์ ์ง์ ํ์ฌ ๊ฐ์ฒด ๊ตฌ์กฐ๋ฅผ ๋ ๋ช ํํ๊ฒ ์ ์ํ ์ ์๋ค.
interface User {
name: string;
age: number;
}
const user: User = {
name: 'Alice',
age: 30,
};
์ฌ๊ธฐ์๋ name์ value๋ string์ด์ด์ผ ํ๊ณ age๋ numer์ฌ์ผ ํ๋ค๋ ๊ฒ์ ๋ช ํํ๊ฒ ์ ์ํ๊ณ ์๋ค.
์ด๊ฑธ ๋ง์ฝ Record๋ก ๋ฐ๊ฟ๋ณธ๋ค๋ฉด ์ด๋จ๊น?
type User = Record<'name' | 'age', string|number>;
const user: User = {
name: 'Alice',
age: '30', // ์ฃผ์! ๊ฐ์ด 'string'์ผ๋ก ์ง์ ๋์์
};
Record๋ฅผ ์ฌ์ฉํ๋ฉด name๊ณผ age๋ผ๋ key์ value๋ก string, number ๋ ๋ค ํ์ฉํ๋๋ฐ, ์ฌ๊ธฐ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค.
value๋ก String๊ณผ Number ๋ชจ๋๋ฅผ ๋ฐ์ ์ ์๊ธฐ ๋๋ฌธ์
name์ Number๊ฐ ๋ค์ด๊ฐ๋, age์ String์ด ๋ค์ด๊ฐ๋ ์๋ฌ๊ฐ ๋์ง ์๋๋ค.
์ด๊ฑด ๊ฐ๋ฐ์๊ฐ ์ํ๋ ๊ทธ๋ฆผ์ ์๋ ๊ฒ์ด๋ค.
๊ฒฐ๋ก ์ ์ผ๋ก Record๋ value์ ํ์ ์ด ๋ชจ๋ ๋์ผํ ๋ ์ฌ์ฉํด์ผ ์์ ์ ์ผ๋ก ์ฌ์ฉํ ์ ์๋ค.
๐ง ์ธ์ interface๋ฅผ ์ฌ์ฉํ๊ณ , ์ธ์ Record๋ฅผ ์ฌ์ฉํด์ผ ํ ๊น?
1. interface ์ฌ์ฉ ์ํฉ
- ๊ตฌ์ฒด์ ์ธ ๊ตฌ์กฐ๋ฅผ ๋ช ์์ ์ผ๋ก ์ ์ํ๊ณ , ๊ฐ์ฒด๊ฐ ํน์ ์์ฑ์ ๊ฐ์ ธ์ผ ํ ๋ ์ฌ์ฉ.
- ํ์ฅํ๊ฑฐ๋, ์ธํฐํ์ด์ค๋ฅผ ๋ค๋ฅธ ํ์ ๊ณผ ํฉ์ฑํ ๋ ์ ์ฉ.
- interface๋ ๋ค์ํ ์์ฑ์ ๋ค๋ฃจ๋ ๋ณต์กํ ๊ฐ์ฒด์ ์ฌ์ฉ.
interface Person {
name: string;
age: number;
greet(): void;
}
const person: Person = {
name: 'John',
age: 25,
greet() {
console.log(`Hello, my name is ${this.name}`);
},
};
2. Record ์ฌ์ฉ ์ํฉ
- ์ ํด์ง ํค์ ๋ํด ๋์ผํ ํ์ ์ ๊ฐ์ ๊ฐ์ง๋ ๊ฐ์ฒด๋ฅผ ๋ค๋ฃฐ ๋ ์ฌ์ฉ.
- ํค๊ฐ ๋ช ํํ๊ฒ ์ ํด์ ธ ์์ ๋, ์์ฑ๋ค์ด ๋์ผํ ํ์ ์ ๊ฐ์ง๋ ๊ฐ์ฒด๋ฅผ ์ ์ํ ๋ ์ ์ฉ.
- ๋์ ์ผ๋ก ์์ฑ๋ ํค๋ ์ ์ฐํ ํค์ ๋ํด ๊ฐ ํ์ ์ ์ ์ํ ๋ ์ฌ์ฉ.
type Status = Record<"pending" | "completed" | "failed", boolean>;
const taskStatus: Status = {
pending: false,
completed: true,
failed: false,
};
'TypeScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TypeScript] unknown vs any (0) | 2025.03.06 |
---|---|
[TypeScript] TypeScript ์ ์ธ๊น์? (0) | 2025.03.06 |