ch2. 기본 타입과 함수 타입 정의

2021. 6. 11. 22:28

본 포스트는 타입스크립트 공식홈페이지와 인프런 강의를 참고합니다.

본 포스팅에 쓰이는 Github 주소입니다. https://github.com/CheoljongPaek/TypeScript2021

 

CheoljongPaek/TypeScript2021

타입스크립트의 기본에 대한 모든것. Contribute to CheoljongPaek/TypeScript2021 development by creating an account on GitHub.

github.com

기본 타입, 함수 타입?

 

 
 

배울 내용

  1. 기본 타입 [문자열, 숫자, 배열, 튜플, 객체, 진위값]
  2. 함수 타입 [파라미터와 반환값, 파라미터를 제한하는 특성, 옵셔널 파라미터]

1. 기본 타입

 

[문자열, 숫자] 우선, 변수를 선언하고 그 변수의 타입을 지정해보자.

// TS Declare of STRING
const str: string = 'hello';
// TS Declare of NUMBER
const num: number = 10;

간단하게 변수 뒤에 : type 을 적어주면 된다. 나머지는 아래와 같다.

 

[배열, 튜플, 객체, 진위값]

// TS Declare of Array
const arr1: Array<number> = [1,2,3];
const arr2: Array<string> = ['a', 'b', 'c'];
const arr3: number[] = [1,2,3]
// TS Declare of Tuple
const tuple: [string, number] = ['isString', 1]
// TS Declare of Object
const obj1: object = {};
const obj2: {name: string, age: number} = {
  name: 'CJPAEK',
  age: 100,
};
// TS Declare of Boolean
const choice: boolean = true;

튜플은 배열의 각 인덱스에 타입을 지정한 것이다.

객체는 { property: type }으로 변수와 프로퍼티 둘의 타입을 지정할 수 있다.

 

 

2. 함수 타입

 

[파라미터와 반환 값]

//TS Declare of Parameter
function sum(a: number, b: number) {
  return a + b;
}
sum(10, 20);

//TS Declare of function return value
function add(a: number, b: number): number {
  //return value is necessary with its proper type.
  return a + b;
}

함수 타입은 기본적으로 파라미터와 그 반환 값 둘 모두의 타입을 정의해서 쓰인다.

 

[파라미터를 제한하는 특성]

function sum1(a: number, b: number): number {
  return a + b;
}
sum1(1,2,3) // Expected 2 arguments, but got 3

 TS는 함수의 규칙을 정확하게 이해하고 있는 상태이기 때문에 위처럼 인자가 3개였을 때 에러가 생긴다.

 

 [옵셔널 파라미터]

위의 파라미터를 제한하는 특성 때문에 sum1(a, b) 또는 sum2(a, b, c)처럼 여러 함수를 만들 필요는 없다.파라미터 뒤에 '?'를 넣어 사용한다.
//Optional Parameter
function log(greeting: string, name?: string) {
  return `${greeting} ${name}`;
}
log('hello'); // hello
log('hi', 'CJPAEK'); // hi CJPAEK

선택적으로 파라미터가 1개일 때와 2개일 때 모두 실행된다.

 

 

👏이제 답할 수 있어야 하는 것들

하나, 함수와 객체의 타입 선언 방식은?
둘, 파라미터의 사용을 선택적으로 할 수 있게 하는 방법은?

'TypeScript' 카테고리의 다른 글

ch1. 타입스크립트를 사용하는 이유 (수정중)  (4) 2021.06.11

Related Articles

more