📌 type alias(타입별칭)

1
type Animal = string | number;
  • type 타입변수명 = 타입종류
  • 이런 식으로 타입 별칭으로 변수처럼 담아서 재사용할 수 있다.
  • 관습적으로 대문자 사용

🏓 function type 지정하기

1
2
3
4
5
6
7
8
9
type NumOut = (x: number, y: number) => number;

let ABC: NumOut = function (x, y) {
return x + y;
};
function removeDash(x: string): number {
let result = x.replace(/-/g, "");
return parseFloat(result);
}
  • 위와 같이 함수 타입도 type alias를 저장하여 사용할 수 있다.
  • 함수타입을 사용하려면 함수를 표현식으로 정의해줘야한다.

callback 함수 type 지정하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type CutType = (x: string) => string;

let cutZero: CutType = function (x) {
let result = x.replace(/^0+/, "");
return result;
};
function removeDash(x: string): number {
let result = x.replace(/-/g, "");
return parseFloat(result);
}

const newFunc = (str: string, funA: CutType, funB: (x: string) => number) => {
return removeDash(cutZero(str));
};
  • 만약 콜백 함수의 타입을 지정해주고 싶다면 위와 같이 지정해줄 수 있다.

✏️ readonly로 객체 잠그기

1
2
3
4
5
const person = {
name: "yiju",
};

person.name = "loco";
  • 위와 같이 자바스크립트에서 const 키워드로 재할당을 막아도 객체 내부까지는 막을 수 없다. 이럴 때 readonly 타입을 지정해주면 막을 수 있다.
1
2
3
4
5
const person = {
name: "yiju",
};

person.name = "loco"; // Error
  • 컴파일 시 에러가 발생한다.(변환된 js 파일은 바뀌어 있다.)

  • readonly number[ ]는 배열 요소를 읽을 수만 있다.

  • 배열을 변경하는 pop 메서드를 비롯한 다른 메서드를 호출할 수 없다.

❗️ readonly 주의사항

1
2
3
const a: number[] = [1, 2, 3];
const b: readonly number[] = a;
const c: number[] = b; // Error: 'readonly number[]는 변경가능한 number[] 타입에 할당할 수 없다.
  • number[ ]는 readonly number[ ]보다 기능이 많기 때문에 readonly number[ ]의 서브타입이다.
  • number[ ]는 readonly number[ ]에 할당 가능하다.
1
2
3
4
5
6
7
function arraySum(arr: readonly number[]) {
let sum = 0;
for (const num of arr) {
sum += num;
}
return sum;
}
  • 함수가 매개변수를 변경하지 않는다면 readonly로 선언해야한다.

⛳️ type 키워드 여러개 합치기

1
2
3
type Name = string;
type Age = number;
type person = Name | Age;
  • OR 연산자를 사용하여 유니온 타입으로 만들 수 있다.
1
2
3
4
5
6
7
8
type PositionX = { x: number };
type PositionY = { y: number };

type XandY = PositionX & PositionY;
type XandZ = PositionX & { z: number };

let pos: XandY = { x: 1, y: 2 };
let pos: XandZ = { x: 10, z: 3 };
  • 객체 타입은 & 연산자를 사용하여 **합치기(extends)**가 가능하다.
  • XandY type is { x: number, y: number }
  • Type alias & Type alias 뿐만 아니라 Type alias & { key: type }도 가능하다.

type 키워드는 재정의가 불가능하다.

❗️ & 연산자 주의사항

1
2
3
4
5
type Combined = { a: number } & { b: string };
type Conflicting = { a: number } & { a: string };

const ta: Combined = { a: 1, b: "st" }; // 정상
const tt: Conflicting = { a: 1 }; // Error
  • Combined 타입은 { a: number, b: string }
  • Conflicting 타입은 { a: number와 string의 교집합 === never }