전체 글
TIL | Interface VS Type
Interface VS Type Alias Interface 인스턴스를 생성하는 class 처럼, 특정한 규칙을 담고 있는 것을 구현할 때 사용하는 것이 적절하다. 1. 기존에 존재하는 인터페이스의 프로퍼티 확장 interface Person { name: string; age: number; } // interface Person { gender: string; } // const yongmin: Person = { name: "yongmin", age: 29, gender: "male", }; 기존 존재하던 인터페이스에 새로운 프로퍼티를 추가할 수 있다. 동일한 이름의 인터페이스에 추가하고자 하는 프로퍼티 값만 적어주면 된다. (공식문서에서는 동일한 인터페이스가 존재할 경우, 해당 필드값들을 merg..
TIL | Generics
Generics(제네릭) 제네릭은 재사용성이 높은 컴포넌트를 만들 때 자주 활용된다. 즉, 특정 타입에 고정되지 않고 여러 타입에서 동작할 수 있는 컴포넌트를 생성하는데 사용된다. 마치 타입을 함수의 변수처럼 유동적으로 지정하여 사용하는 것을 뜻한다. 제네릭은 선언 시점이 아닌, 생성 시점에 타입을 명시하여 다양한 타입의 사용을 가능케 한다. 제네릭을 사용하는 이유 제네릭을 사용하지 않을 경우 const getValue1 = (value: number): number => { return value; }; console.log(getValue1(15)); // 15 // const getValue2 = (value: string): string => { return value; }; console.log..
TIL | Interface
Interface(인터페이스) 인터페이스는 상호간에 정의한 약속 혹은 규칙을 뜻한다. (쉽게 설명하면 사용 설명서같은 느낌도 든다.) 객체의 속성, 함수의 매개변수 및 리턴값, 배열 및 객체의 접근 방식, 클래스에 대해 인터페이스를 지정할 수 있다. (타입의 틀을 정할 수 있다.) 객체에서의 인터페이스 // 객체 interface Person { name: string; age: number; gender?: string; // ?을 통한 옵션 속성 사용(선택적으로 사용 가능) } // const tomas: Person = { name: "tomas", age: 20, }; // const james: Person = { name: "james", age: 30, gender: "male", }; //..
TIL | Type Inference
Type Inference(타입 추론) Inference TS에서 변수 명에 특정 값을 할당할 때, 타입을 따로 명시하지 않았을 경우 알아서 타입이 자동으로 결정되는 것을 말한다. let text = "hello"; // let text: string // text = 1; // Type 'number' is not assignable to type 'string' 위처럼 text 변수 명에 hello를 할당하였더니 변수 타입이 string으로 추론되어 자동으로 결정되었다. 이후 타입이 number값인 1을 재할당하니 에러가 발생한다. (기존의 text 타입이 string으로 결정되었기 때문이다.) Intersection in default const print = (message = "안녕하세요") =..
TIL | Union, Intersection
Union, Intersection Union(|, or) type Direction = "right" | "left" | "up" | "down"; //string Literal Types // const move = function (direction: Direction) { console.log(direction); }; move("right"); // const print = (value: string | number) => { console.log(value); }; print(1); // 1(number) print("1"); // 1(string) JS의 논리연산자중 OR을 뜻하는 ||와 같이 A이거나 B이거나를 뜻한다. 위 move 함수의 인자로 Direction 타입을 지정하였으며, 해당..
TIL | Alias
Alias Alias - primitive type type Text = string; // string을 Text라는 타입으로 지정 const name: Text = "Yongmin"; // type Num = number; // number를 Num이라는 타입으로 지정 const age: Num = "29"; 위처럼 원하는 타입 명으로 타입을 직접 지정할 수 있다.(ex> Text, Num) Alias - object type type Text = string; type Number = number; / type Student = { name: string; // (property) name: string age: number; // (property) name: number }; // const s..