๐ฃ ๋ค์ด๊ฐ๊ธฐ ์ ์!
๊ฐ์ฒด์๋ ํ์
์ด ์กด์ฌํ๋ค!_! ๋น์ฐํ ์ฌ์ค..! ๋๋ฅ! ๊ทธ๋ฌ๋ฉด ์ด๋ฒ์๋ ๊ฐ์ฒด์ ํ์
๊ณผ readonly์ ๋ํด์ ์ดํด๋ณด์!_! ๊ฐ๋จํ๋ ์งง์ ๊ธ์ด ๋๊ฒ ๋ฐ!
ํน์ ์ง๋ ๊ฒ์๋ฌผ์ด ๊ถ๊ธํ๋ค๋ฉด?
[TypeScript] Narrowing ๊ณผ Assertion
๐ฃ ๋ค์ด๊ฐ๊ธฐ ์ ์!์ด๋ฒ์๋ Narrowing & Assertion์ ๋ํด์ ์ดํด๋ณผ ๊ฒ์ด๋ค. ํน์ ์ง์ง๋ ๊ฒ์๋ฌผ์์ ๋ค๋ค๋ union type์์ ์ค๋ฅ๊ฐ ๋ฌ๋ ๋ถ๋ถ๋ค์ ๊ธฐ์ต ํ๋์ง?!?! ๋๋ต ์๋์ ๊ฐ์ ์ฝ๋์๋๋ฐ, ์ฌ๊ธฐ์
haileyham.tistory.com
๊ฐ์ฒด์ ํ์
2ํ interface ๊ธ์ด ๊ถ๊ธํ๋ค๋ฉด?
[TypeScript] ๊ฐ์ฒด์ ํ์
interface
๐ฃ ๋ค์ด๊ฐ๊ธฐ ์ ์!์ด๋ฒ์๋ ๊ฐ์ฒด์ ํ์
2ํ์ธ ๊ฒ์ธ๊ฐ! ์ง๋๋ฒ ๊ฐ์ฒด์ ํ์
์ ์ ๋ฆฌํ ๋๋ readonly์ ๋ํด์๋ง ๋ค๋ค์๋๋ฐ, ์ด๋ฒ์๋ interface์ ๋ํด์ ๋ค๋ค๋ณด์ ๊ฐ์ฒด์ ํ์
๊ธฐ๋ณธ๊ฐ๋
๊ณผ readonly
haileyham.tistory.com
๐ฃ ๊ฐ์ฒด์ ํ์
1. ๊ฐ๋
๊ฐ์ฒด์ ํ์
์ TypeScript์์ ๋ณ์๋ ์์ฑ์ด ๊ฐ์ง ์ ์๋ ๊ตฌ์กฐ์ ํ์
์ ์ ์. ํด๋น ๊ฐ์ฒด๊ฐ ์ด๋ค ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ํฌํจํ๊ณ ์๋์ง๋ฅผ ๋ช
์ํ๋ฉฐ, ์ฝ๋์์ ๋ช
ํํ ํ์
๊ฒ์ฌ์ ์๋ฌ ๋ฐฉ์ง๋ฅผ ๊ฐ๋ฅํ๊ฒ ํจ.
2. ์ฝ๋๋ก ์ดํด๋ณด๊ธฐ
์๋์ ์ฝ๋์์๋ type alias(ํ์
๋ณ์)๋ฅผ ์ด์ฉํ์ฌ ๊ฐ์ฒด์ ํ์
์ ์ ์ํ์.
// ์์ : ์ฌ์ฉ์ ๊ฐ์ฒด์ ํ์
์ ์
type User = {
name: string;
age: number;
isAdmin: boolean;
};
// User ํ์
์ ๊ฐ์ง ๊ฐ์ฒด ์์ฑ
let user: User = {
name: "Alice",
age: 30,
isAdmin: true
};
console.log(user.name); // "Alice"
console.log(user.isAdmin); // true
๋ง์ฝ ํ์
๋ณ์์ ๋ํ ๊ฐ๋
์ ๋ชจ๋ฅธ๋ค๋ฉด ์๋ ์ ๋ฆฌ๊ธ ์ฐธ๊ณ !_!
[TypeScript] ํ์
๋ณ์ type alias
๐ฃ ๋ค์ด๊ฐ๊ธฐ ์ ์!์ด๋ฒ์ type alias์ ๋ํด์ ์ดํด๋ณด๊ฒ ๋ค. ์ฌ์ค type alias๋ผ๊ณ ํ๋ฉด ์ผ์? ํ ์๋ ์๋๋ฐ, ํ์
์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉํ๊ณ ์๋ค๋ฉด ๋ค๋ค ๋ง์ด ์ฌ์ฉํ๋ ๊ฒ์ด๋ค. ๊ทธ๋ฅ type์ ๋ณ์์ ๋ด์ ์ฌ
haileyham.tistory.com
๐ฃ readonly
1. ๊ฐ๋
readonly ํค์๋๋ ๋ณ์๋ ์์ฑ์ ์ฝ๊ธฐ ์ ์ฉ์ผ๋ก ์ ์ธํ ๋ ์ฌ์ฉ. ์ด๋ฅผ ํตํด ๊ฐ์ด ํ ๋ฒ ํ ๋น๋๋ฉด ๋ณ๊ฒฝํ ์ ์๊ฒ ๋จ.
2. ํน์ง
const ๊ฐ์ฒด ์ฌํ ๋น์ ๋ชปํ๊ฒ ํ ์ ์์! const ๋ณ์๋ ๋ฑํธ๋ก ์ฌํ ๋น ๋ง๋๋ฐ, ๊ฐ์ฒด์ ๊ฒฝ์ฐ ์์ ์ด ์์ ๋กญ๊ฒ ๊ฐ๋ฅํจ
* ์ฐธ๊ณ : ๊ฐ์ฒด ์ฌํ ๋น ๋๋ ์ด์ ๋ ๋ณ์์ ํ ๋น๋ ์ฃผ์๊ฐ์ ์ฐธ์กฐํ๊ณ , ๊ฐ์ฒด๋ฅผ ์ฌํ ๋น ํ ๊ฒฝ์ฐ ์ฃผ์๊ฐ์ ๋ณํ์ง ์๊ธฐ ๋๋ฌธ. ๊ทธ๋์ const ํค์๋ ์ ์ธ ํ์ ๋ฐ์ดํฐ ๋ณ๊ฒฝ ๊ฐ๋ฅ
const ์ถ์์ง์ญ = { region: 'seoul' }
์ถ์์ง์ญ.region = 'universe'
// readonly ์ฌ์ฉํ์ฌ object ์๋ฃ ์์ ๋ง๊ธฐ
type Animal2 = {
readonly name : string //์ค์๋ก ์์ ํ๋ฉด ์๋ฌ๋ฐ์์ํด
}
const ๋๋ฌผ2 : Animal2 = {
name : 'cat'
}
3. ์ฝ๋๋ก ์ดํด๋ณด๊ธฐ
// readonly ํค์๋๋ฅผ ์ฌ์ฉํ์ฌ ์์๋ฅผ ์ ์
const PI: number = 3.14;
console.log(PI);
// readonly๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด์ ์์ฑ์ ์ฝ๊ธฐ ์ ์ฉ์ผ๋ก ์ ์
type Circle = {
readonly radius: number;
};
let circle: Circle = { radius: 10 };
console.log(circle.radius);
// ๋ค์๊ณผ ๊ฐ์ด ์์ฑ์ ๋ณ๊ฒฝํ๋ ค๊ณ ํ๋ฉด ์ค๋ฅ๊ฐ ๋ฐ์
// circle.radius = 20; // Error: Cannot assign to 'radius' because it is a read-only property
์ต๊ทผ ํ๋ก์ ํธ์ readonly๋ฅผ ์ฌ์ฉํ ๊ธฐ์ต์ด ๋๋๊ตฌ๋ง..
[TypeScript] ํ์
๋ณ์ type alias
๐ฃ ๋ค์ด๊ฐ๊ธฐ ์ ์!์ด๋ฒ์ type alias์ ๋ํด์ ์ดํด๋ณด๊ฒ ๋ค. ์ฌ์ค type alias๋ผ๊ณ ํ๋ฉด ์ผ์? ํ ์๋ ์๋๋ฐ, ํ์
์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉํ๊ณ ์๋ค๋ฉด ๋ค๋ค ๋ง์ด ์ฌ์ฉํ๋ ๊ฒ์ด๋ค. ๊ทธ๋ฅ type์ ๋ณ์์ ๋ด์ ์ฌ
haileyham.tistory.com