자린이 시절 마구잡이 타입스크립트

태태·2023년 6월 15일
0
const person  = {name:’ellie’ , age:21}

console.log(person.name);
console.log(person[’name’]);

은 동일하게 값에 접근할 수 있다

Key가 있는 obj에는 다음과 같이 반복문을 작성

const obj = { name:’taetae’ , age:21}
for (key in obj) {
	console.log(key);
}
// name
// age

value가 있는 iterable한 요소에는 다음과 같이 반복문을 작성

const array = [1,2,3,4,5]
for (value of array) {
	console.log(value);
}
1
2
3
4
5

forEach 콜백함수 사용

//function
array.forEach(function (num, index) {
	console.log(num, index);
});

//애로우펑션으로 변환
array.forEach((num, index) => {
	console.log(num, index);
});

//리턴값이 한줄이면 중괄호 생략
array.forEach((num, index) => console.log(num,index);

object 복사하는 법

const user = { name:'ellie' , age:20 }
/** 방법1 */
const user_copy = user; //원본과 가리키는 레퍼런스가 같아서 원본이 수정됨

/** 방법2 */
const user_copy = {}; //빈 오브젝트생성
for (key in user) { // for문으로 수동적 할당
	user_copy[key] = user[key];
}

/** 방법3 */
const user_copy = {};
Object.assign(user_copy, user); //assign을 사용
/** 혹은 */
const user_copy = Object.assign({}, user);

/** 방법4 */
const user_copy = { ...user }; // spread 연산자 활용

RegExp.prototype.test()

test() 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 true 또는 false 로 반환한다

const str = 'table football';

const regex = new RegExp('foo*');
const globalRegex = new RegExp('foo*', 'g');

console.log(regex.test(str));
// expected output: true

console.log(globalRegex.lastIndex);
// expected output: 0

console.log(globalRegex.test(str));
// expected output: true

console.log(globalRegex.lastIndex);
// expected output: 9

console.log(globalRegex.test(str));
// expected output: false

then 함수

자바스크립트에서 함수는 동기함수, 비동기 함수로 나뉜다. 우리가 작성한 코드들은 위에서 아래로 순차적으로 코드가 실행되고 하나의 코드가 종료되지 않는다면 다음 코드로 넘어가지 않는다. 이것이 동기함수이다.API를 호출할 때, 사용하는 fetch 함수는 대표적인 비동기함수이다. 그렇기 때문에 API호출하는 과정이 끝나지 않더라도 자동적으로 다음 코드로 넘어간다. 하지만 API로부터 받아온 정보를 사용할 필요가 있는 경우에 .then함수를 쓰는 것이다.


제너릭 사용법

function getSize(arr: number[] | string[] | boolean[] | object[]): number {
	return arr.length;
}
const arr1 = [1,2,3];
getSize(arr1);
const arr2 = ["a","b","c"];
getSize(arr2);
const arr3 = [false, true, true];
getSize(arr3);
const arr4 = [{}, {}, {name: "Time}];
getSize(arr4);

와 같은 코드를

function getSize<T>(arr: T[]): number {
	return arr.length;
}
const arr1 = [1,2,3];
getSize<number>(arr1);
const arr2 = ["a","b","c"];
getSize<string>(arr2);
const arr3 = [false, true, true];
getSize<boolean>(arr3);
const arr4 = [{}, {}, {name: "Time}];
getSize<object>(arr4);

과 같이 타입추론을 하여 사용가능


map, forEach 메서드와 Promise

다음과 같은 경우에 map, forEach 함수는 Promise를 반환하지 않으므로 Promise() 메서드로 감싸준 뒤 await로 처리하여야 한다

let flag = true;

array.map(v => {
	if (v === false) {
    	flag = false;
    	return;  	
    }
});

console.log(flag); // 무조건 true로 찍힘
let flag = true;

await Promise.all(
	array.map(v => {
    	if (v === false) {
          flag = false;
          return;
        }
    });
);

console.log(flag) // map 안의 flag 할당을 반영함
profile
과정에서 재미를 느끼지 않는데 성공하는 일은 거의 없다

0개의 댓글