TypeScript 제어문 & 연산자

김대현·2020년 3월 24일
3

TypeScript 이론 정리

목록 보기
2/5
post-thumbnail

TypeScript 제어문 & 연산자

1. 반복문

ES6의 for of 문

인덱스를 이용해 값을 가져올 수 있는 for in 문과 달리 for of 문은 곧바로 값을 가져올 수 있다. 이터러블(iterable)은 반복 가능한 객체인 배열, 문자열, DOM 컬렉션, 맵(Map)과 셋(Set) 등을 말한다.

//for in
let fruits = {"a" : "apple", "b" : "banana", "c": "cherry"};

for (let property in fruits) {
  console.log(property, fruits[property]); // a apple b banana c cherry
}
//for of
for (const value of [1,2,3]) {
  console.log(value); // 1, 2, 3
}

일반 for 문에서는 let 선언자가 아닌 const를 사용할 수 없다. for of 문은 Symbol.iterator의 구현을 통해 각 이터레이션 값의 요소를 가져오기 때문에 const를 사용할 수 있다는 사실!

맵과 셋을 for of 문에 적용

ES6에 추가된 이터러블 객체로 맵(Map)셋(Set)이 있다. 맵 객체는 키 중복을 허용하지 않는 자료구조이다.

//Map은 key의 중복을 허용하지 않는다.
let itMap = new Map([["one", 1], ["one", 2]]);
itMap.set("one", 3);

for (let entry of itMap) 
  console.log(entry); // ['one', 3]

//Set은 어떤 타입의 값이든 유일한 값을 저장할 수 있다.
let isSet = new Set(["a", "b", "c", "d", "a", "b", "c"]);

for (let vlaue of itSet) 
  console.log(value); //a b c d

[Symbol.iterator]() 메서드를 이용한 이터러블 객체 사용

배열, 맵, 셋과 같은 이터러블 객체를 순회하는 데 사용한다.

let arr = [1, 2];
let itObj = arr[Symbol.iterator]();

console.log("1:", typeof itobj); //object
console.log("2:", itObj.next()); //value:1, done: false
console.log("3:", itObj.next()); //value:2, done: false
console.log("4:", itObj.next()); //value: undefined, done: true

2. 연산자

기본 연산자

  • 비교 연산자 ===, >=, <, ...

    타입 스크립트에서 "==" 연산자 대신 "==="을, "!=" 연산자 대신 "!=="을 사용하기를 권장하는 이유는 자바스크립트로 컴파일하고 나서도 타입 안정성을 보장할 수 있기 때문이다.

  • 논리 연산자 &&,||,!

    truthy, falsy에 대해... 우리는 코딩을 하면서 자주 이런 에러를 만나게 된다. Cannot read property 'name' of undefined. 항상 객체의 property에 접근할때는 해당 객체가 undefined인지 check logic을 넣어야한다. 아래의 예제를 보면 name property를 사용하기 위해 animal을 체크 한다. 마지막으로 name도 비어 있는 값인지 체크한다.

function getName(animal: { name: string }):string  {
  let name:string = '';
  if (animal) {
    name = animal.name;
  }
  if (!name)
    return '이름이 없는 동물';
  else
    return name;
}

//위의 예제처럼 쓸 수 있지만 논리 연산자를 사용하면 이렇게 줄일 수 있다.
function getName(animal: { name: string }):string  {
  return (animal && animal.name) || '이름이 없는 동물';	
}

https://dev-momo.tistory.com/entry/Javascript-Optional-Chaining

  • 조건 연산자 ?:

타입스크립트는 ES7의 지수 연산자인 **를 지원하므로 Math.pow를 대체해서 사용할 수 있다.

console.log(10 ** 3); // 1000
console.log(1 + "happy"); // 1happy

디스트럭처링

타입스크립트는 ES6의 디스트럭처링(destructuring)을 지원한다. 디스트럭처링이라는 말의 뜻은 객체의 구조(structure)를 제거(de)한다는 의미가 있다. 디스트럭처링은 객체의 구조를 분해 후 할당이나 확장과 같은 연산을 수행한다.

  • 객체 디스트럭처링

    객체 디스트럭처링은 객체 리터럴에서 변수명에 대응하는 속성 값을 추출해 변수로 할당하는데 유용하다.

let { id, country = 88 } = { id: "happy" }; //default value 설정
console.log(country); //88
let { id: newName1, country: newName2 } = { id: "happy", country: 88 };
console.log(newName1); //happy

const deepObject = {
  state: {
    information: {
      name: 'tom',
      language: ['korean', 'english', 'japanese']
    }
  },
  value: 5
}

const {
  state: {
    information: {
      name, language
    }
  }
} = deepObject
console.log(name) // tom
  • 디스트럭처링 매개변수 선언
/*
** 객체의 속성에 각각의 property가 있는지 체크 후에 값을 할당하고 있다. 
*/
function printProfile(obj) {
  let name = "";
  let nation = "";
  name = obj.name ? "none" : obj.name;
  nation = obj.nation? "?" : obj.nation;
  console.log(name); //happy
}

/*
** property를 매개변수에서 체크하면 좀 더 효율적인 코드가 될 수 있다.
*/
function printProfile({ name = "none", nation = "?" }) {
  console.log(name); //happy
}

function printProfile2({ name, nation = "?" } = { name: "none" }) {
  console.log(name, nation); //happy
}
printProfile2(); //none ?
//type 키워드를 이용해 매개변수의 타입을 선언하는 예제
type C= { a: string, b?: number };
function fruit({ a, b }: C): void {
  console.log(a, b);
}

fruit({ a: "apple" }); //apple, undefined
//매개변수 b는 number 타입이고 선택 연산자인 ?로 선언했으므로 생략 가능
  • 배열 디스트럭처링
let numbers = ["one", "two", "three", "four", "five"];
let [,,num3, num4] = numbers;
console.log(num3, num4); //three, four

전개 연산자

타입스크립트는 ES6의 전개 연산자(spread operator)를 지원한다. 전개 연산자는 '...'로 나타내는데 다음 세 가지 경우에 사용된다.

  • 나머지 매개변수를 선언할 때
  • 배열 요소를 확장할 때
  • 객체 요소를 확장할 때
//배열 concat 예제
let arr: number[] = [1,2];
let arr2: number[] = [...arr, 3, 4];
console.log(arr2); //[1,2,3,4]

//rest를 사용한 전개 연산자 (배열)
let [first, ...rest]: number[] = [10, 20, 30];
console.log(first) //10
console.log(rest) //[20, 30]

//rest를 사용한 전개 연산자 (객체)
let numGroup = { n1: 1, n2: 2, n3: 3 };
let { n2, ...rest } = numGroup;
console.log(n2, n13);  //2 { n1: 1, n3: 3 } 

함수 인자와 spread

배열의 원소들의 합을 출력하는 함수를 만든다고 해보자. 배열을 인자로 받은 후에 for문 돌려서 return을 하는 것이 그려지는가? 이런 방법도 있다는 것을 알아보자.

function sum(...rest:number[]):number {
  return rest.reduce((acc, current) => acc + current, 0);
}

const numbers = [1,2,3,4,5,6];
const result = sum(...numbers);
console.log(result); //21

내친김에 최대값도 해보자. rest와 reduce를 이용하면 이렇게 깔끔해질 수 있다.

function max(...rest:number[]):number {
  const sum = rest.reduce((acc, current) => (acc < current ? current : acc), 0);
  return sum;
}
const result = max(1, 2, 3, 4, 5, 6);
console.log(result);
profile
FrontEnd Developer with React, TypeScript

0개의 댓글