본문 바로가기

Language/TypeScript18

클래스 ■ 클래스 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.
readonly, index Signature, Mapped Types ■ readonly interface A { readonly a: string; b: string; } const a: A = { a: "hello", b: "world" }; a.a = "123"; // readonly 읽기 전용 속성으로 할당 불가 ■ index Signature type B = { [key: string]: string; }; const b: B = { a: "1", b: "2" }; ■ Mapped Types type C = "Human" | "Animal" | "Plant"; // 파이프(|) 쓸 때는 type으로. interface 는 and 와 or 이 안됨. type D = { [key in C]: number }; const c: D = { Human: 1, Animal:.. 2023. 2. 20.
{} , Object ■ {} , Object 는 모든 타입을 의미 const x: {} = "hello"; const y: Object = "hi"; // {}, Object 는 모든 타입(null과 undefined 제외) const x1: object = "hi"; // [ERROR] string 형식은 object 형식에 할당할 수 없다. const x2: object = { hello: "world" }; ■ unknown 도 모든 타입 받을 수 있다. const z: unknown = "h1"; // unknown 도 모든 타입 받을 수 있으나 사용시 타입 지정해주어야 함 // unknown = {} | null | undefined if (z) { // 해당 조건문에서 null 과 undefined 가 제외 z;.. 2023. 2. 19.
커스텀 타입 가드 ■ 커스텀 타입 가드 타입을 구분해주는 커스텀 함수를 만들 수 있음. interface Cat { meow: number; } interface Dog { bark: number; } // 리턴 값에 is 키워드가 들어가 있으면 커스텀 타입 가드 함수 function catOrDog(a: Cat | Dog): a is Dog { // 타입 판별은 직접 코딩 if ((a as Cat).meow) { return false; } return true; } 커스텀 타입 가드 함수는 if 문 안에서 사용 function pet(a: Cat | Dog) { if (catOrDog(a)) { console.log(a.bark); } if ("meow" in a) { console.log(a.meow); } } 2023. 2. 18.