문서의 이전 판입니다!
아래의 예제를 정상적으로 실행해보실려면 tsconfig.json에서 compilerOptions의 target 속성을 es6로 해 주셔야 합니다.
일반적으로 Destructuring Assignment(비구조할당)라고 하는데 쉽게 말하자면 배열의 요소나 객체의 속성을 배열 literal 혹은 객체 literal과 유사한 형태의 문법을 이용하여 변수에 할당하는 기법입니다. 잘 알아두면 코드를 좀 더 쉽게 작성할 수 있습니다.
다음과 같이 배열이 있을 경우 각 배열의 원소값을 가지는 변수를 만들려고 합니다. 아마도 코드는 다음처럼 써야 할 듯 보입니다.
let myArr: string[] = ["Hello", "World", "Moon"]; let first: string = myArr[0]; let second: string = myArr[1]; let third: string = myArr[2]; console.log(first); // "Hello" 출력 console.log(second); // "World" 출력 console.log(third); // "Moon" 출력
이 코드를 Destructuring Assignment(비구조할당)를 이용하면 다음과 같이 표현할 수 있습니다.
let myArr: string[] = ["Hello", "World", "Moon"]; let [first, second, third] = myArr; console.log(first); // "Hello" 출력 console.log(second); // "World" 출력 console.log(third); // "Moon" 출력
위의 코드에서 [first, second, third] 형태를 Destructuring Array(비구조배열)이라고 합니다. 즉, let [first, second, third] 구문은 변수 선언과 동시에 Destructuring Array(비구조배열)을 생성한 것입니다.
만약 Destructuring Array(비구조배열)에 data type을 지정하고 싶은경우는 다음과 같이 하시면 됩니다.
let myArr: string[] = ["Hello", "World", "Moon"]; let [first, second, third]: string[] = myArr;
간단한 응용을 보도록 하죠. 두개의 변수에 대한 swap처리입니다. 기본적으로는 임시변수가 있어야 두 변수의 값을 swap처리 할 수 있지만 Destructuring Assignment를 이용하면 보다 간단하게 할 수 있습니다.
let myArr: string[] = ["Hello", "World"]; let [first, second] = myArr; console.log(first); // "Hello" 출력 console.log(second); // "World" 출력 [second, first] = [first, second]; // swap 처리 console.log(first); // "World" 출력 console.log(second); // "Hello" 출력
이런 방식은 함수에 parameter를 전달할 때도 사용할 수 있습니다.
function myFunc([x, y]: [number, number]): void { console.log(`x의 값은 ${x}`); console.log(`y의 값은 ${y}`); } myFunc([10,20]);
나머지 몇몇 응용에 대해서 알아보겟습니다. …을 이용하면 다음과 같은 형태로 서브배열을 생성할 수 있습니다.
let myArr: number[] = [1, 2, 3, 4]; let [first, ...others] = myArr; console.log(first); // 1 출력 console.log(others); // [2, 3, 4] 출력 ( 서브배열 )
다음과 같은 형태로 Destructuring Array를 이용할 수 있습니다.
let myArr: number[] = [1, 2, 3, 4]; let [first] = myArr; let [,second, ,fourth] = myArr; console.log(first); // 1 출력 console.log(second); // 2 출력 console.log(fourth); // 4 출력