Lucky Charms Clover

❔ TypeScript

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 타입 조작

타입 조작 기본 타입이나 별칭, 인터페이스로 만든 원래 존재하던 타입들을 상황에 따라 유동적으로 다른 타입으로 변환시키는 기능 제네릭을 비롯해 4가지 타입 조작 기능(인덱스드 엑세스 타입, keyof 연산자, Mapped 타입, 템플릿 리터럴 타입)에 대해 알아보자. 인덱스드 엑세스 타입 객체, 배열, 튜플 타입으로부터 특정 프로퍼티나 특정 요소의 타입만 추출한다. type Post = { title: string; content: string; author: { id: number; name: string; age: number; }; }; const post: Post = { title: '제목', content: '본문', author: { id: 1, name: 'summermong', age: ..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 프로미스와 제네릭

프로미스와 제네릭 Promise는 제네릭 클래스로 구현되어 있다. 따라서 새로운 Promise를 생성할 때 타입 변수에 할당할 타입을 직접 설정하면 해당 타입이 resolve 결과값의 타입이 된다. const promise = new Promise((resolve, reject) => { setTimeout(() => { // 결과값 : 20 resolve(20); }, 3000); }); promise.then((response) => { // response는 number 타입 console.log(response); }); promise.catch((error) => { if (typeof error === "string") { console.log(error); } }); reject 함수에 인수..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 제네릭 클래스

제네릭 클래스 class NumberList { constructor(private list: number[]) {} push(data: number) { this.list.push(data); } pop() { return this.list.pop(); } print() { console.log(this.list); } } const numberList = new NumberList([1, 2, 3]); numberList.pop(); numberList.push(4); numberList.print(); NumberList라는 클래스를 만들었다. private를 붙이면 필드를 따로 지정하지 않아도 되고, 생성자 함수 내에서도 별도로 this.~ 를 적을 필요가 없다. 따라서 private로 접근 제어..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 제네릭 인터페이스

제네릭 인터페이스 제네릭은 인터페이스에도 적용할 수 있다. 인터페이스에 타입 변수를 선언해 사용하면 된다. interface KeyPair { key: K; value: V; } let keyPair: KeyPair = { key: 'key', value: 1, }; let keyPair2: KeyPair = { key: true, value: ['1'], }; 키페어를 저장하는 객체 타입을 제네릭 인터페이스로 정의했다. 변수 keyPair에서는 타입으로 KeyPair를, keyPair2에서는 KeyPari을 정의했다. 그러면 key에는 K = string | boolean, V = number | string[]으로 정의되게 된다. 제네릭 인터페이스는 제네릭 함수와 달리 변수의 타입으로 정의할 때, 반..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] map, forEach 메서드 타입 정의하기

제네릭을 이용한 JS의 배열 메서드 map, forEach 구현 map 구현 const arr = [1, 2, 3]; const newArr = arr.map((it) => it * 2); function map(arr: unknown[], callback: (item: unknown) => unknown): unknown[] {} 배열 arr에 map과 콜백 함수를 적용해 새로운 배열 newArr을 만들었는데, 이를 TS와 제네릭으로 구현해보려 한다. 먼저 메서드를 적용할 배열 arr과 콜백 함수 callback을 매개변수로 받아준다. 이 때 두 매개변수의 타입은 우선 모두 unknown으로 해주고, 함수의 반환값 타입도 unknown[]로 지정해준다. function map(arr: T[], call..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 제네릭 활용

제네릭을 활용하자 function swap(a: T, b: U) { return [b, a]; } const [a, b] = swap("1", 2); 2개의 타입 변수가 필요한 위와 같은 상황에서는 타입 변수를 T, U 이렇게 2개를 사용할 수 있다. function returnFirstValue(data: T[]) { return data[0]; } let num = returnFirstValue([0, 1, 2]); // number let str = returnFirstValue([1, "hello", "mynameis"]); // number | string 다양한 배열 타입을 인수로 받는 제네릭 함수를 만들어야 한다. 함수 매개변수 data의 타입을 T[]로 설정했기 때문에 배열이 아닌 값은 인..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 제네릭

제네릭 함수나 인터페이스, 타입 별칭, 클래스 등을 다양한 타입과 함께 동작하도록 만들어주는 TS의 기능 제네릭 함수는 두루두루 모든 타입의 값을 적용할 수 있는 범용적인 함수다. function func(value: any) { return value; } let num = func(10); // any 타입 let str = func("string"); // any 타입 다양한 타입의 매개변수를 받고 해당 매개변수를 그대로 반환하는 함수를 만들려고 한다. 이 때 다양한 타입의 매개변수를 받기 위해 매개변수의 타입을 any로 정의했다. 그랬더니 누가 봐도 10, string인 변수의 타입이 any로 고정되어 버렸다. 이는 func 함수의 반환값 타입이 return문을 기준으로 any라고 추론되었기 때문..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 인터페이스와 클래스

인터페이스와 클래스 TS의 인터페이스는 클래스의 설계도 역할을 할 수 있다. 인터페이스를 이용해 클래스에 어떤 필드가 존재하고, 어떤 메서드가 존재하는지 정의할 수 있다. interface CharacterInterface { name: string; moveSpeed: number; move(): void; } // 인터페이스로 클래스를 구현하다 // 인터페이스는 무조건 pubulic class Character implements CharacterInterface { constructor(public name: string, public moveSpeed: number) {} move(): void { console.log(`${this.moveSpeed} 속도로 이동`); } } CharacterI..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 접근 제어자

접근 제어자(Access Modifier) 클래스의 특정 필드나 메서드에 접근할 수 있는 범위를 설정하는 기능 TS에는 pubilc(모든 범위에서 가능), private(클래스 내부에서만 가능), protected(클래스/파생 클래스 내부에서만 가능)이 있다. public class Employee { // 필드 name: string; // 자동으로 public age: number; // 자동으로 public position: string; // 자동으로 public // 생성자 constructor(name: string, age: number, position: string) { this.name = name; this.age = age; this.position = position; } // 메..

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 타입스크립트의 클래스

타입스크립트의 클래스 타입스크립트에서도 똑같이 클래스를 만들기 전 객체를 만들어보자. const employee = { name: 'summermong', age: 27, position: 'developer', work() { console.log('일함'); }, }; 이런 객체를 찍어낼 클래스 Employee를 만든다. class Employee { // 필드 name: string; age: number; position: string; // 생성자 constructor(name: string, age: number, position: string) { this.name = name; this.age = age; this.position = position; } // 메서드 work() { con..

썸머몽
'❔ TypeScript' 카테고리의 글 목록 (2 Page)