자바스크립트에 타입이 추가된 개념?

  • 자바 스크립트에 타입을 추가하여 자바스크립트를 확장 시킨다.
  • 실행 전 자바스크립트를 해석함으로 사용자의 소스를 수정하는 시간을 절약할 수 있다.
  • 모든 브라우저, 운영체제, 자바스크립트 실행 환경에서 제공하는 오픈소스이다.

TypeScript = Language

 

  • 자바스크립트에 있는 기능을 강화시키고 타입이라는 개념이 추가
  • 순수한 자바스크림트로 컴파일 (ts -> js)
  • 타입스크립트는 'Programming Language 언어'
  • 타입 스크립트는 'compiled Language'
    1. 전통적인 Compiled Language와는 다른 점이 많음
    2. 'Transpile'이라는 용어를 사용하기도 함

 

※ 자바스크립트는 'Interpreted language' 

 

 

Compiled  vs  Interpreted

컴파일이 필요함 컴파일이 필요하지 않음
컴파일러가 필요함 컴파일러가 필요하지 않음
컴파일하는 시점함 컴파일하는 시점하지 않음
컴파일된 결과물을 실행 코드를 실행하는 시점
컴파일된 결과물을 실행하는 시점 코드를 실행하는 시점 = 런타임



타입스크립트 프로젝트 설정

 

// 프로젝트 생성
mkdir tsc-project
cd tsc-project

// package.json 파일 생성
npm init -y

// 타입스크립트는 런타임에서 필요하지 않음으로 -D를 붙인다.
npm i typescript -D

// tsconfig.json 파일 생성
npx tsc -init

package.json

npm 환경에서 프로젝트에서 필요한 패키지들을 관리

 

typeScript

프로젝트 컴파일하는 데 필요한 루트 파일과 컴파일러 옵션을 지정

 

'TypeScript' 카테고리의 다른 글

[TypeScript] TypeScript vs JavaScript, Primitive Types  (0) 2023.01.17

변수에 객체를 할당하고 아래와 같이 변수를 복사하고 첫번째 할당한 변수의 값을 변경하면, 복사한 변수의 값도 함께 변경 된다.

 

const user = { name: "lee", age: 20, email: ["test@naver.com"] };
const test01 = user;

console.log(user);
console.log(test01);

user.name = "kim";

console.log(user);
console.log(test01);

 

결과

{name: 'lee', age: 20, email: Array(1)}
age:20
email:['test@naver.com']
name:"kim"
[[Prototype]]:Object

{name: 'lee', age: 20, email: Array(1)}
age:20
email:['test@naver.com']
name:"kim"
[[Prototype]]:Object

{name: 'kim', age: 20, email: Array(1)}age: 20
email:['test@naver.com']
name:"kim"
[[Prototype]]:Object

{name: 'kim', age: 20, email: Array(1)}
age: 20
email:['test@naver.com']
name:"kim"
[[Prototype]]:Object

 

객체의 경우 같은 주소를 참조하기 때문에 원래의 데이터의 값이 바뀌면 복제된 변수도 같은 주소를 참조하기 때문에 같은 값이 출력이 된다.

 

별도의 주소를 할당 받아 데이터를 복제하는 방법으로 두 변수 사이에 영향을 받지 않게 할수 있다.

 

 

1. 얕은 복사(shallow copy)

 

사용법

const user = { name: "lee", age: 20, email: ["test@naver.com"] };

const test02 = Object.assign({}, user);
const test03 = { ...user }; 

user.name = "kim";

console.log(user);
console.log(test02);
console.log(test03);

 

결과

{name: 'kim', age: 20, email: Array(1)}
age:20
email:['test@naver.com']
name:"kim"
[[Prototype]]:Object

{name: 'lee', age: 20, email: Array(1)}
age:20
email:['test@naver.com']
name:"lee"
[[Prototype]]:Object

{name: 'lee', age: 20, email: Array(1)}
age:20
email:['test@naver.com']
name:"lee"
[[Prototype]]:Object

얕은 복사일 경우 객체 내에 존재하는 변수가 변경이 되어도 복사된 변수에서는 다른 메모리 주소를 사용하기 때문에 값이 변경 되지 않는것을 확일할 수 있다.

 

하지만 얕은 복사내에 객체 변수가 존재할 경우 내부에 추가하는 값은 변경된다.

 

const user = { name: "lee", age: 20, email: ["test@naver.com"] };

const test02 = Object.assign({}, user);
const test03 = { ...user }; 

user.email.push("test@gmail.com");

console.log(user);
console.log(test02);
console.log(test03);

 

결과

{name: 'lee', age: 20, email: Array(2)}
age:20
email:(2) ['test@naver.com', 'test@gmail.com']
name:"lee"
[[Prototype]]:Object

{name: 'lee', age: 20, email: Array(2)}
age:20
email:(2) ['test@naver.com', 'test@gmail.com']
name:"lee"
[[Prototype]]:Object

{name: 'lee', age: 20, email: Array(2)}
age:20
email:(2) ['test@naver.com', 'test@gmail.com']
name:"lee"
[[Prototype]]:Object

얕은 복사일 경우는 복사가 되었더라도 객체 내에 또 객체가 존재할 경우에는 같은 메모리 주소를 참조하고 있기 때문에 값이 변경이 된다.

 

이런 경우는 lodash에서 제공하는 깊은 복사를 사용하면 된다.

 

2. 깊은복사(Deep copy)

사용법

const user = { name: "lee", age: 20, email: ["test@naver.com"] };
const test04 = _.cloneDeep(user);

user.email.push("test@gmail.com");

console.log(user);
console.log(test04);

 

결과

{name: 'lee', age: 20, email: Array(2)}
age:20
email:(2) ['test@naver.com', 'test@gmail.com']
name:"lee"
[[Prototype]]:Object

{name: 'lee', age: 20, email: Array(1)}
age:20
email:(2) ['test@naver.com']
name:"lee"
[[Prototype]]:Object

깊은 복사 일 경우는 객체내에  타입이 객체인 변수가 변경되더라도 복사된 변수의 값이 변경되지 않는것을 알 수 있다.

'JavaScript' 카테고리의 다른 글

[JavaScript] Lodash 란?  (0) 2023.01.11
[JavaScript] 타이머 함수  (0) 2023.01.02
[JavaScript] 객체의 타입얻기  (0) 2022.12.23

Lodash (https://lodash.com)

→ 모듈성, 성능 및 추가 기능을 제공하는 최신 JavaScript 유틸리티 라이브러리이다

 라이센스는 MIT 라이센스로 Object, Array 등의 데이터 구조를 쉽게 변환하는 기능을 제공해준다.

 

설치

npm i -g lodash

 

import

import _ from "lodash"

※ 기본적으로 _ 로  명시해주나, _가 아닌 다른 이름으로 하여도 됨.

 

1. defaultTo

 

기본값 설정 값이 있으면 해당 값을 저장, 값이 비어있으면(null or undefined) 경우 기본값을 저장

 

사용법

let a = 100;
a = _.defaultTo(a, 1);
console.log("100 default :", a);

a = undefined;
a = _.defaultTo(a, 1);

console.log("undefined default :", a);

a = "";
a = _.defaultTo(a, 1);
console.log('"" default :', a);

a = null;
a = _.defaultTo(a, 1);
console.log("null :", a);

결과

100 default : 100
undefined default : 1
 "" default : 
null : 1

 

2. uniqBy unionBy

중복된 값이 있을 때 중복된 값을 제거

 

사용법

const fruit1 = [
  { id: 1, name: "apple" },
  { id: 2, name: "banana" },
  { id: 3, name: "cherry" },
];
const fruit2 = [
  { id: 2, name: "orange" },
  { id: 4, name: "apple" },
];

// 두개 배열 병합
const fruit = fruit1.concat(fruit2);
// 중복 제거
const uniqBy = _.uniqBy(fruit, "id");

// 병합 후 중복제거
const unionBy = _.unionBy(fruit1, fruit2, "id");

console.log("fruit1:", fruit1);
console.log("fruit2:", fruit2);
console.log("fruit:", fruit);
console.log("fruit uniqBy:", uniqBy);
console.log("fruit unionBy:", unionBy);

한개의 배열에서 중복을 제거할 때는 uniqBy 두개 이상의 배열을 병합 시 중복제거 할 때는 unionBy를 사용한다.

 

결과

fruit1: (3) [{…}, {…}, {…}]
0: {id: 1, name: 'apple'}
1: {id: 2, name: 'banana'}
2: {id: 3, name: 'cherry'}
length: 3[[Prototype]]: Array(0)

fruit2: (2) [{…}, {…}]
0: {id: 2, name: 'orange'}
1: {id: 4, name: 'apple'}
length: 2[[Prototype]]: Array(0)

fruit: 
(5) [{…}, {…}, {…}, {…}, {…}]
0:{id: 1, name: 'apple'}
1:{id: 2, name: 'banana'}
2:{id: 3, name: 'cherry'}
3:{id: 2, name: 'orange'}
4:{id: 4, name: 'apple'}
length: 5[[Prototype]]:Array(0)

fruit uniqBy: 
(4) [{…}, {…}, {…}, {…}]
0:{id: 1, name: 'apple'}
1:{id: 2, name: 'banana'}
2:{id: 3, name: 'cherry'}
3:{id: 4, name: 'apple'}
length:4[[Prototype]]:Array(0)

fruit unionBy: 
(4) [{…}, {…}, {…}, {…}]
0: {id: 1, name: 'apple'}
1: {id: 2, name: 'banana'}
2: {id: 3, name: 'cherry'}
3: {id: 4, name: 'apple'}
length: 4[[Prototype]]: Array(0)

 

 

3. find, findIndex

 

배열 내에 조건에 해당하는 데이터 찾기 또는 데이터의 인덱스 찾기

 

사용법

console.log("fruit find :", _.find(uniqBy, { id: 2 }));
console.log("fruit findIndex :", _.findIndex(uniqBy, { id: 2 }));

결과

fruit find : {id: 2, name: 'banana'}
fruit findIndex : 1

4. remove

 

배열의 조건에 해당하는 데이터 삭제

 

사용법

_.remove(uniqBy, { id: 2 });
console.log("fruit remove :", uniqBy);

 

결과

fruit remove : (3) [{…}, {…}, {…}]
0:{id: 1, name: 'apple'}
1:{id: 3, name: 'cherry'}
2:{id: 4, name: 'apple'}
length:3[[Prototype]]:Array(0)

 

5. shuffle, sortBy, sortBy revers

 

배열의 순서 랜덤으로 섞기, 배열의 오름차순, 내림차순정렬

 

사용법

const shuffle = _.shuffle(fruit);
console.log("fruit shuffle :", shuffle);
const sort = _.sortBy(shuffle, "id");
console.log("fruit sortBy :", sort);
const reverse = sort.reverse();
console.log("fruit sortBy revers:", reverse);

 

결과

fruit shuffle :(5) [{…}, {…}, {…}, {…}, {…}]
0:{id: 2, name: 'banana'}
1:{id: 2, name: 'orange'}
2:{id: 4, name: 'apple'}
3:{id: 1, name: 'apple'}
4:{id: 3, name: 'cherry'}
length:5[[Prototype]]:Array(0)

fruit sortBy :(5) [{…}, {…}, {…}, {…}, {…}]
0:{id: 1, name: 'apple'}
1:{id: 2, name: 'banana'}
2:{id: 2, name: 'orange'}
3:{id: 3, name: 'cherry'}
4:{id: 4, name: 'apple'}
length:5[[Prototype]]:Array(0)

sortBy revers:(5) [{…}, {…}, {…}, {…}, {…}]
0:{id: 4, name: 'apple'}
1:{id: 3, name: 'cherry'}
2:{id: 2, name: 'orange'}
3:{id: 2, name: 'banana'}
4:{id: 1, name: 'apple'}
length:5[[Prototype]]:Array(0)

 

 

 

+ Recent posts