[TIL] TypeScript-함수 작성법

link717·2021년 3월 22일
0

TIL

목록 보기
40/53
post-thumbnail

🌼 함수의 타입 명시

🌻 함수의 반환(Return) 타입

function 함수이름(매개변수1, 매개변수2): 함수의 반환 타입 {
}


function sendGreeting (message, userName): void {
  console.log(`${message}, ${userName}`);
}

sendGreeting('Hello', 'Mark');
// void: 아무것도 반환하지 않는 함수의 반환 값으로만 사용될 수 있는 타입


function sendGreeting (message, userName): string[] {
  return ['Hello', 'Mark'];
}
// 원시 type 외에 배열이나 객체 형태도 type으로 지정할 수 있다.

🌻 함수의 매개변수(Parameter)

function sendGreeting (message: string, userName: string): void {
  console.log(`${message}, ${userName}`);
}

sendGreeting('Hello', 1);
// 다른 타입의 매개변수는 전달되지 않고 에러를 발생시킨다.

sendGreeting('Hello');
// 함수 호출시, 타입 스크립트 컴파일러는 함수에 정의된 Parameter와
// 함수를 호출할 때 전달된 Argument의 수를 확인하여 일치하지 않을 경우,
// 에러를 발생시킨다.


// 매개변수를 선택적으로 전달될 수 있는 상황이라면 선택적 매개변수 처리를 한다.
function sendGreeting (message: string, userName?: string): void {
  console.log(`${message}, ${userName}`);
}

sendGreeting('Hello');
// Hello, undefined
// 선택적 매개변수는 필수 매개변수 뒤에 위치해야 한다!

🌻 함수의 기본 매개변수

function sendGreeting (message: string, userName = 'there'): void {
  console.log(`${message}, ${userName}`);
}

sendGreeting('Hello');
// Hello, there
// userName의 type을 삭제한 이유는 타입 스크립트에 타입 추론이 있기 때문이다.
function sendGreeting (message = 'Hello', userName = 'there'): void {
  console.log(`${message}, ${userName}`);
}


sendGreeting();
// Hello, there
sendGrerting('Good morning');
// Good morning, there
sendGreeting('Good afternoon', 'Jenny');
// Good afternoon, Jenny

출처: YOUTUBE-땅콩코딩

profile
Turtle Never stop

0개의 댓글