Types

Yeonn·2023년 8월 17일

TypeScript

목록 보기
2/4
post-thumbnail

1. function

1-1. optional Parameter

정해진 타입을 전달할 수도 있고, 없을 수도 있다.(undefined)

const printName = (firstName: string, lastName?: string) => {
  console.log(firstName);
  console.log(lastName); 	// 없을 경우 undefined 출력
}

printName('Tia', 'Kim');
printName('Tia');
printName('Tia', undefined);

1-2. Default Parameter

따로 인자를 전달받지 않은 경우 지정된 default 값이 출력된다.

const printMessage = (message: string = 'default message') => {
  console.log(message);
}

printMessage();

1-3. Rest Parameter

함수 내에서 가변적인 수의 인수를 배열로 수집하는 방법이다. 함수가 명시적으로 선언된 파라미터 수 이상의 인수를 받을 수 있다.

const addNumbers = (...numbers: number[]): number => {
  return numbers.reduce((a, b) => a+b);
}

console.log(addNumbers(1, 2); // 3
console.log(addNumbers(1, 2, 3, 4, 5); //15

2. array

const fruits: string[] = ['🍅', '🍌']
const fruits: Array<string> = ['🍅', '🍌']

위의 두 가지 방법으로 array 타입을 지정할 수 있다. 이 때, string[]readonly 가 사용 가능하지만 Array<string>readonly가 사용이 불가하다.

readonly
오브젝트의 불변성 보장
주어진 데이터를 변경하거나 업데이트 하지 못하도록 타입 보장

3. tuple

고정된 사이즈에 서로 다른 타입을 묶어주고자 할 때 사용하지만 interface, alias, class 등 좀 더 명시적으로 사용할 수 있는 방법을 지향한다. 데이터 접근을 index로 해야하는 것은 가독성이 떨어지기 때문이다.

let student: [string, number];
student = ['name', 123];
student[0] // name
student[1] // 123

4. alias

type 별칭 = 타입;

type alias 는 새로운 타입을 정의하는 것이다. 원시 타입에 별칭을 정의하는 것은 지양한다.
객체에 타입을 지정하는 경우 유용하게 활용할 수 있다. 객체를 생성할 때 마다 모든 객체의 모든 요소들 마다 타입을 지정하는 것은 코드를 불필요하게 길어지게 한다.
이 때 객체의 기본 타입을 alias로 정의하고 객체를 생성할 수 있다.

type Student = {
  name: string;
  age: number;
}

const Tia: Student = {
  name: 'Tia',
  age: 1,
}

const Anne: Student = {
  name: 'Anne',
  age: 1,
}

5. union (= OR, |)

발생할 수 있는 모든 경우를 부여하고 그 중 하나의 값을 이용하고자 할 때 사용

5-1. optional type

let person : string | null;

const sayHi = (name: string | undefined) =>{
  //...
}

5-2. switch, if 문 등과 함께

type Command = 'add' | 'substract' | 'multiply' | 'devide';
const calculate = (command: Command, x: number, y: number): number => {
  switch(command) {
    case "add":
      return x + y;
    case "substract":
      return x - y;
    case "multiply":
      return x * y;
    case "divide":
      return x / y;
    case "remainder":
      return x % y;
    default:
      throw new Error("unknown command");
  }
};

console.log(calculate("add", 1, 3)); // 4
console.log(calculate("substract", 3, 1)); // 2
console.log(calculate("multiply", 4, 2)); // 8
console.log(calculate("divide", 4, 2)); // 2
console.log(calculate("remainder", 5, 2)); // 1

5-3. discriminated

union 타입은 함수를 호출하는 시점에 '지정한 타입 중 하나가 올 수 있음'으로 판단하기 때문에 '어느 타입이 올지 모른다' 로 인식한다. 이 때문에 어느 타입이 들어오든 오류가 나지 않는 방향으로 타입을 추론한다.
그래서 두 타입이 공통적으로 가지고 있는 속성만 활용 가능하다.

6. intersection ( =AND, & )

여러 타입을 모두 만족하는 하나의 타입이다.

type Student = {
	name: string;
	score: number;
};

type Worker = {
	employeeId: number;
	work: () => void;
};

const internWork = (person: Student & Worker) => {
	console.log(person.name, person.employeeId, person.work());
}

internWork({
	name: 'Tia',
	score: 1,
	employeeId: 123,
	work: () => {},
});

7. Enum

관련된 여러 개의 상수 값들을 한 곳에 모아서 정의할 수 있도록 도와주는 타입이다. 맨 앞글자만 대문자로 표기하고, 주로 union으로 대체되어 사용된다.

 enum Days {
    Monday, // 0
    Tuesday, // 1
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
  }

8. inference

타입이 원시타입인 경우에는 타입을 생략해도 괜찮지만 함수 등의 경우에는 타입을 작성해야 한다.

✅ 처음 선언과 동시에 할당된 값의 타입으로 정의된다.
✅ 인자는 아무 타입도 지정하지 않으면 any 지정된다.
✅ 타입 추론 : 인자들을 통해 함수의 return 값의 타입이 추론된다.

9. assertion

개발자가 컴파일러에게 명시적으로 타입을 전달하는 방법도 있으나, 쓰지 않는 것이 추천된다.

0개의 댓글