본문 바로가기

TypeScript

(12)
[TypeScript] Utility Types 유틸리티 타입(Utility Types) : 타입스크립트에서 타입을 쉽게 변환할 수 있게 해준다. Partial : 모든 속성이 옵셔널로 변경된 타입을 반환 interface User { id: number; name: string; username: string; address: { road_address: string; detail_address: string; zipcode: string; lat: number; lng: number; }; phone: string; isAdmin: boolean; isStaff: boolean; level: number; } type UserFormType = Partial; // type UserFormType = { // id?: number | undefin..
[TypeScript] 조건부 타입 조건부 타입 : 타입을 조건적으로 부여할 수 있다. ex) SomeType extends OtherType ? TrueType : FalseType; // SomeType 이 OtherType 에 할당할 수 있다면 TrueType 없으면 FalseType interface User { name: string; } interface Student extends User { studentId: number; } type Example1 = Student extends User ? number : string // type Example1 = number 보통 Generics과 함께 사용됨 throw() : 사용자 정의 예외를 발생(throw)할 수 있습니다. 예외가 발생하면 현재 함수의 실행이 중지됩니다. ..
[TypeScript] Mapped Type 맵드 타입(Mapped Type) : 기존에 정의되어 있는 타입을 새로운 타입으로 변환 type OptionsFlags = { [Property in keyof T]: boolean; }; type Input = { value: string; onChange: () => void; disabled: boolean; }; type InputOptions = OptionsFlags; // type InputOptions = { value: boolean; onChange: boolean; disabled: boolean; } readonly 추가 type CreateMutable = { // +readonly, readonly : 없던 readonly 붙혀줌 +readonly [Property in keyo..
[TypeScript] Index Signature 인덱스 시그니처(Index Signature) : 객체의 키 이름을 아직 모르고 있고, 타입만 알고 있는 경우 사용 주의사항 : 어떤 타입이 올지 알 수 있는 상황이라면 인덱스 시그니처를 사용하기보다는 최대한 정확하게 타입을 정의하는 것을 권장 interface UserType { [index: string]: string; } 인덱스 타입 쿼리 연산자(keyof) : 객체 타입에서 키들을 리터럴의 유니언 타입으로 가져온다. type Point = {x: number, y: number}; type P = keyof Point; // type P = 'x' | 'y' 와 같음 type Arr = { [n:number]:unknown}; type A = keyof Arr; // type A = number..
[TypeScript] Type Guard 타입 가드(Type Guard) : 어떤 스코프 안에서 특정 타입을 보장하는 런타임 검사를 수행한다는 표현식 타입 선언(as) : 타입 추론이 정확하지 않을 때 혹은 의도와 다르게 추론하고 있을 때, as 키워드를 사용해서 타입을 단언 const a:string = 'hi'; const b = (a as string).length; const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement; 타입 서술어(is) : 리턴 타입이 타입 서술어(predicate)인 함수를 정의하여 사용 매개변수명 is 타입 type Fish = { swim: () => void }; type Bird = { fly: () => void }; fun..
[TypeScript] Generics 제네릭(Generics)이란 단일 타입이 아닌 다양한 타입에서 작동하는 컴포넌트를 작성할 수 있으며, 사용처에서 타입을 정해서 전달해줄 수 있다. function identity (arg:T):T { return arg; } const identity2: (arg:T) => T = (arg) => { return arg; } type IdentityType = (arg:T) => T; const identity3: IdentityType = (arg) => { return arg; } 제네릭 타입 변수 function identity (arg:T):T { return arg; } let output = identity("myString"); function identity (arg:T[]):T[] { c..
[TypeScript] Class 클래스 : JS 에서는 ES2015의 새로운 문법으로 TS 에서는 클래스 기능은 C# 에서 유래된 것이 많다. 일부 기능은 TS 에서만 존재하는 고유 문법으로 컴파일 후에 사라진다. ▶ 생성자 & 메서드 // class class Person { name: string; age: number; readonly location: string = "Korea" // 수정 방지(readonly) // 생성자(초기화 담당) : class 가 만들어질 때 필요 constructor(name: string, age: number) { // this 는 생성될 인스턴스를 바라본다. this.name = name this.age = age } // 메서드(행동) introduce(): string { return `$..
[TypeScript] Literal Types 리터럴 타입 (Literal Type) : 고정된 값을 타입으로 가짐 var 또는 let 으로 변수를 선언할 경우 변수의 값을 변경할 수 있다. 하지만 const로 변수를 선언하게 되면 TypeScript에게 이 객체는 절대 변경되지 않음을 알린다. let A = 123; let B = 456 as const; // 타입 단언하기 (const assertion) const C = 789; A => let A : number B => let B: 456 C => const C: 789 문자열 리터럴 타입 (String Literal Types) Color 에서 허용한 4개의 문자열 외에 다른 문자열을 사용하게 되면 에러가 발생 type Color = "red" | "orange" | "yellow" | "..