공부/TypeScript(6)
-
TypeScript #7 Utility type
타입스크립트는 유틸리티 타입(utility type)을 제공하여, 기존 타입을 변환하거나 새로운 타입을 생성할 수 있는 기능을 제공합니다. 유틸리티 타입을 사용하면, 반복적으로 사용되는 타입 패턴을 간단하게 작성할 수 있습니다. 타입스크립트에서 제공하는 대표적인 유틸리티 타입은 다음과 같습니다. Partial: 모든 속성이 선택적으로 정의된 T 타입을 생성합니다. Required: 모든 속성이 필수적으로 정의된 T 타입을 생성합니다. Readonly: 모든 속성이 읽기 전용으로 정의된 T 타입을 생성합니다. Record: 키가 K 타입이고, 값이 T 타입인 객체 타입을 생성합니다. Pick: T 타입에서 K 속성만을 선택하여 타입을 생성합니다. Omit: T 타입에서 K 속성을 제거하여 타입을 생성합니다..
2023.03.14 -
TypeScript #6 Generic
제네릭(Generic)은 TypeScript에서 타입 안정성을 유지하면서 재사용성을 높이기 위한 기능입니다. 함수나 클래스를 작성할 때, 그 타입이나 인터페이스를 지정하지 않고 일반화된 형태로 작성할 수 있도록 해줍니다. 이렇게 작성된 함수나 클래스는 나중에 호출되거나 인스턴스화될 때, 타입 인자를 전달하여 구체화할 수 있습니다. //Generic function getSize(arr: number[] | string[] | boolean[]){ return arr.length; } const arr1 = [1,2,3]; getSize(arr1); //3 const arr2 = ['a','b','c']; getSize(arr2); //4 const arr3 = [true, true, false]; get..
2023.03.12 -
TypeScript #5 Class
class Car{ color:string; // constructor(readonly color: string){ // constructor(public color: string){ constructor(color: string){ this.color = color; } start(){ console.log("start"); } } 위와 같은 방법으로 color 프로퍼티의 타입을 정확히 명시해주는 방법으로 명시적인걸 좋아하는 타입스크립트의 컴파일 에러를 방지할 수 있다. 그리고, 주석 처리한 방법중 하나인 public 접근 제한자를 사용하여 'color' 프로퍼티를 선언과 동시에 생성자의 매개변수로 선언. constructor(public color: string) 이러한 경우, 타입스크립트 컴파일러가..
2023.03.12 -
TypeScript #4 Literal/Union/Intersection types
Literal type Literal 타입은 값 자체가 타입으로 사용됨. 즉, 해당 값과 정확하게 일치하는 타입을 가지게 됨. let greeting: "hello" = "hello"; 위와 같이 'greeting' 이라는 변수는 문자열 'hello'만을 가지게 되며, 다른 문자열을 할당하면 타입에러가 발생 Union Types Union 타입은 '|' 연산자를 사용하여 둘 이상의 타입을 결합 할 수 있다. //Union types interface Car{ name:"car"; color:string; start():void; } interface Mobile{ name:"mobile"; color:string, call():void; } function getGift(gift:Car|Mobile){ ..
2023.03.11 -
TypeScript #3 Function
function hello(name: string){ return `Hello, ${name || "World!"}` } //타입스크립트는 명시적인것을 좋아한다. //name이 없으면 World가 출력되어야 하는 코드지만.. //에러가 발생한다 const result = hello(); //hello()함수에는 argument가 필요하다. //아래와 같이 name을 옵셔널로 주는것도 방법이다. function hello(name?: string){ return `Hello, ${name || "World!"}` } const result = hello(); const result = hello("kim"); 매개변수의 순서도 중요하다. 타입스크립트는 명시적인것을 매우 좋아한다. 타입스크립트에서 Rest ..
2023.03.11 -
TypeScript #1 Type
기본 타입 let age:number = 30; let isAdult:boolean = true; let a:number[] = [1,2,3]; let a2:Array = [1,2,3]; let week1:string[] = ['mom', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; let week2:Array = ['mom', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; 튜플 //튜플(Tuple) let b:[string, number]; b = ['z', 1]; // b = [1, 'z'] //오류 b[0].toUpperCase(); //오류없음 // b[1].toUpperCase(); //오류 void, never // void, ne..
2023.03.10