https://github.com/ZeroCho/ts-all-in-one
ts 문법
- interface → 선언 할때마다 합쳐짐
작성된 인터페이스를 커스텀 할 때 사용할 수 있겠다(ex 라이브러리 수정)
interface A { a: string }
interface A { b: string }
const obj1: A = { a: 'hello', b: 'world' }
type B = { a: string }
type B = { b: string } // 중복 시 err
- 잉여 속성 검사
기본적으로 좁은 타입은 넓은 타입에 대입 가능
but 객체 리터럴에는 잉여 속성 검사 존재!
type A = { hello: string };
const a: A = { hello: 'world', why: 'error' }; // err <- 잉여 속성 검사
const b = { hello: 'world', why: 'error' }; // 중간에 새로운 obj 생성 시 허용
const c: A = b;
- void 타입
- 함수 선언 시 void(return 값이 void)
→ 함수의 return 값이 존재하지 않는다!(또는 undefined)
→ return 값이 존재하지 않는다는 의미(return값이 존재할 경우 error) - method로 선언 시 void / 매개변수로 선언한 void
→ return 값을 사용하지 않겠다는 의미(실제 return 값이 존재해도 상관X)
- 함수 선언 시 void(return 값이 void)
- 기본적으로 any를 쓸바에는 unknown을 사용!
- any : 타입 검사 자체를 포기
- unknown : 지금은 해당 타입을 알 수 없다는 의미 → 추후 타입 지정 필요
try {
...
} catch (error) {
// 이 때 error는 unknown 타입!
(error as Error) ...
}
- 타입 가드(type narrowing)
→ typeof, instanceof, in, Array.isArray 등 사용
→ is 를 통한 타입 구분 커스텀 함수 작성도 가능
function numOrStr(a: number | string) {
if (typeof a === 'string') {
a.split(',');
} else {
a.toFixed(1);
}
}
function numOrNumArr(a: number | number[]) {
if (Array.isArray(a)) {
a.slice(1);
} else {
a.toFixed(1);
}
}
type B = { type: 'b', bbb: string };
type C = { type: 'c', ccc: string };
type D = { type: 'd', ddd: string };
type A = B | C | D;
function typeCheck(a: A) {
if (a.type === 'b') {
a.bbb;
} else if (a.type === 'c') {
a.ccc;
} else {
a.ddd;
}
}
interface Cat { meow: number }
interface Dog { bow: number }
function catOrDog(a: Cat | Dog): a is Dog {
if ((a as Cat).meow) { return false }
return true;
}
const cat: Cat | Dog = { meow: 3 }
if (catOrDog(cat)) {
console.log(cat.meow);
}
if ('meow' in cat) {
console.log(cat.meow);
}
- class에 추가된 private, protected
class B implements A {
private a: string; // 상속 받은 class에서는 사용 불가
protected b: string; // 상속 받은 class에서 사용 가능
}
class C extends B {}
new C().a;
new C().b;
'source-code > TypeScript' 카테고리의 다른 글
React 프로젝트에서 TS 사용하기 (0) | 2023.01.12 |
---|---|
ts-all-in-one : 기본 개념 (0) | 2023.01.09 |
ts-all-in-one : utility types (0) | 2023.01.09 |
ts-all-in-one : 기본 문법 (0) | 2023.01.09 |
TS - all in one : 제네릭 (0) | 2023.01.09 |