본문 바로가기

TypeScript16

Partial 타입 interface Profile { name: string; age: number; married: boolean; } const lee: Profile = { name: "lee", age: 30, married: true, }; 위 인터페이스에서 각 프로퍼티를 필수가 아닌 선택이 되도록 하고 싶을때 Partial 타입을 사용할 수 있다. 사용예시 const kim: Partial = { name: "kim", age: 25, }; Partial 타입의 정의는 다음과 같다 type Partial = { [P in keyof T]?: T[P]; }; 각 프로퍼티마다 Optional(물음표)를 붙여주는데 앞서 배운 Index signature와 Mapped types 그리고 괄호표기법을 활용하여 정의하였다.. 2023. 3. 19.
공변성과 반공변성 공변성과 반공변성.. 용어부터가 뭔가 어렵다 강의 들어봤는데 이해하려고 하면 할수록 더 복잡해지는 개념이기에 결론만 기억하고 사용하면 될 것 같다 공변성과 반공변성은 함수 간의 대입에서 나온 개념이다. function a(x: string): number { return +x; } type B = (x: string) => number | string; const b: B = a; 위와 같이 리턴 값은 더 넓은 타입으로 대입이 가능하다. 리턴 값을 넓은 타입에서 좁은 타입으로 대입 하는 것은 불가능하다. function d(x: string): number | string { return +x; } type C = (x: string) => number; const c: C = d; // ERROR 그리.. 2023. 3. 18.
기본값 ■ 타입스크립트 기본값 타입 자리 옆으로 기본값을 넣을 수 있다. const a = (b: number = 1, c: number = 2) => { return b; }; // 기본값이 있으면 optional 이 붙어서 값이 없어도 됨 a(2); // 여기서 a의 타입은 a: (b?: number, c?: number) => number 객체 기본값 const d = (e: { hello: string } = { hello: "world" }) => { return e; }; 제네릭 기본값 const add = (x: T, y: T) => ({ x, y }); 2023. 2. 25.
클래스 ■ 클래스 class A { private a: string; #b: number = 123; // # = private 으로 클래스 내부에서만 사용 가능 // 생성자 constructor(a: string) { // b 에는 기본 값 할당 this.a = a; } } // class 는 타입이 될 수 있음 type B = A; const a: A = new A("123"); const b: typeof A = A; ■ 인터페이스 interface A { readonly a: string; b: string; } class B implements A { a: string = "hello"; b: string = "world"; private c: string = "private"; protected d:.. 2023. 2. 21.