โœจArray์™€ Tuple

๐Ÿ”ท Array


โœ”๏ธ Array ์˜ˆ์ œ1

let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];


โœ”๏ธ Array ์˜ˆ์ œ2

// Array
const fruits: string[] = ["๐Ÿ…", "๐ŸŒ"];
const scroes: Array<number> = [1, 3, 4]; // number[] = [1, 2, 3];

function printArray(fruits: readonly string[]) {
  // readonly ๋ผ๋Š” ํ‚ค์›Œ๋“œ๋Š” ๋ง ๊ทธ๋Œ€๋กœ ์ฝ๊ธฐ ์ „์šฉ
  // object์˜ ๋ถˆ๋ณ€์„ฑ์„ ์ง€ํ‚ค๋Š” ๊ฒƒ์€ ๋งค์šฐ ์ค‘์š”ํ•˜๋ฏ€๋กœ, readonly๊ฐ€ ๋งŽ์ด ์‚ฌ์šฉ ๋จ
}



๐Ÿ”ท Tuple

Tuple์€ ๋ฐฐ์—ด์€ ๋ฐฐ์—ด์ธ๋ฐ ์„œ๋กœ ๋‹ค๋ฅธ ํƒ€์ž…์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ๋ฐฐ์—ด


โœ”๏ธ Tuple ์˜ˆ์ œ1

// Declare a tuple type
let x: [string, number];

// Initialize it
x = ["hello", 10]; // OK

// Initialize it incorrectly
x = [10, "hello"]; // ๐Ÿ’ฉError


โœ”๏ธ Tuple ์˜ˆ์ œ2

Tuple์„ ์‚ฌ์šฉํ•˜๋Š” ๊ณณ์ด๋ผ๋ฉด interface, type alias, class ๋“ฑ์œผ๋กœ ๋Œ€์ฒดํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ์ถ”์ฒœ!

  • Tuple์— ์ ‘๊ทผํ•  ๋•Œ์—”, index๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•œ๋ฐ ์ด๋Ÿฌ๋ฉด ์–ด๋–ค ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด์žˆ๋Š”์ง€ ๋ฐ”๋กœ ํ™•์ธ์ด ์–ด๋ ค์šฐ๋ฏ€๋กœ ๊ฐ€๋…์„ฑ โฌ‡๏ธ โžก๏ธ ์ด๋Ÿฐ ๊ฒฝ์šฐ ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น๋ฅผ ํ™œ์šฉํ•˜์ž!
let student: [string, number];
student = ["name", 123];
student[0]; // name
student[1]; // 123
const [name, age] = student; // ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น Destructuring


โœ”๏ธ Tuple ์˜ˆ์ œ3 useState()

useState(): ์ฒซ ๋ฒˆ์งธ์™€ ๋‘ ๋ฒˆ์งธ์˜ ํƒ€์ž…์ด ๋‹ค๋ฅด๋‹ค. ๋‘ ๋ฒˆ์งธ๋Š” ํ•จ์ˆ˜ํ˜•

const [num, setNum] = useState(null);