본문 바로가기
  • 살짝 구운 김 유나

TS5

[TypeScript] Utility Type 타입스크립트에서는 타입을 변환하는 것이 가능하다. - 한 타입의 일부분을 새로운 타입으로 이용 가능 - 한 타입을 기본으로 하여 다른 타입으로 이용 가능 Index Type : 특정 타입의 Index에 기반한 타입 객체의 value는 다음과 같이 접근 가능하다. const obj = { name: "yuna", }; obj.name; // yuna obj["name"]; // yuna Animal이라는 타입을 선언한 뒤, 타입의 인덱스에 기반한 타입을 새로운 타입으로 사용할 수 있다. type Animal = { name: string; age: number; gender: "male" | "female"; }; type Name = Animal["name"]; //string const text: Na.. 2023. 3. 5.
[TypeScript] 제네릭 (Generics) 다음 코드의 문제점은 number 타입에 대한 유효성 검사만 가능하다는 것이다. function checkNotNullBad(arg: number | null): number { if (arg == null) { throw new Error("not Valid Number!"); } return arg; } any 타입을 사용하는 것도 좋지 않은 방법임 => 타입이 보장되지 않기 때문 function checkNotNull(arg:any | null): any { if (arg == null) { throw new Error('not valid number!') } return arg; } const result = checkNotNull(123); 이때, Generic을 사용할 수 있다. 아래의 함수에.. 2023. 3. 1.
[TypeScript] 객체지향 (OOP) 절차 지향 : 정의된 순서대로(절차적으로) 함수가 하나씩 호출됨 하나를 수정하기 위해서 전체적인 어플리케이션을 이해해야함 수정했을때 side Effect가 발생할 수 있음 한눈에 이해하기 어렵다 Coffee Maker 예제) { /** * 절차지향적 프로그래밍 */ type CoffeeCup = { shots: number; hasMilk: boolean; }; const BEANS_GRAMM_PER_SHOT: number = 7; let coffeebeans: number = 0; function makeCoffee(shots: number): CoffeeCup { // 커피 콩이 부족하다면 if (coffeebeans < shots * BEANS_GRAMM_PER_SHOT) { throw new Er.. 2023. 2. 24.
[TypeScript] 기본 타입 #2 Type Alias (타입 별칭) : 타입의 새로운 이름을 만들어 직접 타입을 정의할 수 있음 /** * Type Aliases * 새로운 타입을 내가 정의할 수 있음 */ // 원시타입 type Text = string; const name: Text = "yuna"; const address: Text = "korea"; type Num = number; // Object 타입 type Student = { name: string; age: number; }; const yuna: Student = { name: "유나", age: 24, }; String Literal Types : 타입을 값 자체로 지정할 수 있음 해당 타입으로 선언된 변수는 지정된 문자열의 값만 할당 가능 /** * String.. 2023. 2. 22.
[TypeScript] 기본 타입 #1 기본 타입 { /** * JavaScript * Primitive : number, string, boolean, biginy, symbol, null, undefined * Object: function, array... */ // number const num: number = -3.0; // string const str: string = "hello"; // boolean const bool: boolean = true; // undefined - 아직 알지 못하는 값 let name: undefined; // ❌ 이렇게 하면 undefined만 할당 가능 let age: number | undefined; // 숫자 또는 undefined age = undefined; age = 12; func.. 2023. 2. 21.