본문 바로가기
typescript

🖇 타입스크립트 함수

by frontChoi 2025. 1. 18.
반응형

⚱️ 함수 매개변수 / 반환 타입 정하기

play함수에는 musicIdUrl을 string으로 받고, artist을 string으로 받은 다음 2개의 문자를 하나로 합쳐서 리턴하는 형태이다.

여기서 매개변수와 리턴타입을 string으로 주었다.

// 함수에는 매개변수와 반환하는것에 타입을 줄 수 가 있다.
function play(musidUrl: string, artist: string): string {
  return musidUrl + "/" + artist;
}

play("music_0000","artist1")
// music_0000/artist1 리턴

 

 

📤 선택적 매개변수

모든 함수의 변수를 필수로 줄 필요는 없다. ?를 통해서 선택적 매개변수를 주는것이 가능하다

// 선택적 매개변수
// 필수적인 값이 아닐때 사용된다.
// 여기서는 artist가 옵션으로 받도록 설정되어있다
function broadCastMusic(musicId: string, artist?: string): string {
  if (artist) {
    return `${musicId}/${artist}`;
  }

  return musicId;
}
// 2번째 인자를 넣지 않아도 오류가 나지 않는다
broadCastMusic("musicid00000");
broadCastMusic("musicid00000", "artist");

 

 

📕 기본값 초기화

//기본값 초기화
// 기본값을 초기화 하고 싶을때 사용된다
// 기본값에 따라 타입추론이 가능하다(artist를 "none"으로 했으므로 string으로 추론이 가능하다)

function broadCastMusicInfo(musicId: string, artist = "none"): string {
  return musicId + "/" + artist;
}

//아래 처럼 호출할 경우 artist는 기본적으로 none이 된다
broadCastMusicInfo("musicid0000");

 

 

📊 나머지 매개변수

변수가 얼마나 들어올지 모를 경우 사용된다

spread문법으로 표현한다 ...artist:string[]으로 표현하면 개수 상관없이 string을 받을 수 있다

// 나머지 매개변수
// 필수와 나머지 변수를 여러개 받을때 필요
// spread문법으로 표현할 수 있다
function restOfArtist(artist1: string, ...artist: string[]): string {
  return artist1 + "/" + artist.join("");
}

// 
restOfArtist("music1", "artist2", "artist3");

 

 

🗳 this 매개변수

javascript에서는 this는 어디서 호출하느냐에 따라 다르다.

객체의 매서드의 this는 객체를 가르키고, 객체의 매서드 안에 함수가 있는 경우에는 window 또는 global를 가르킨다

typescript에서는 this를 정확히 가르키는것이 낫다

// 건강 기록 row 이며 category,date으로 구성
interface HistoryItem {
  category: string;
  date: string;
}

// 건강기록 인터페이스 이며 catergory리스트와 , history는 HistoryItem의 배열, addHistory함수가 있다.
interface History {
  category: string[];
  history: HistoryItem[];
  addHistory(this: History): () => HistoryItem;
}

// 건강기록 객체 이며,타입은 History이다
const historyHealth: History = {
  category: ["hungerpain", "headache"],
  history: [
    {
      category: "hungerpain",
      date: "2025-01-18",
    },
    {
      category: "headache",
      date: "2025-01-19",
    },
  ],
  // 객체의 매서드의 함수의 경우 this는 window 또는 global이다. 다만, 화살표함수의 경우 자신의 상위 스코프의 
  // this를 따른다
  // 인자에 this의 타입을 정하지 않을 경우 this가 any로 추론된다. 그러므로 this에 History타입을 선언한다
  addHistory: function (this: History) {
    return () => {
      const date = new Date();
      const yyyy = date.getFullYear();
      const mm =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : `0${date.getMonth() + 1}`;
      const dd = date.getDate() > 9 ? date.getDate() : `0${date.getDate()}`;

      return {
        category: this.category[0],
        date: `${yyyy}-${mm}-${dd}`,
      };
    };
  },
};

const add = historyHealth.addHistory();
const { category, date } = add();
console.log(category, date);
반응형

'typescript' 카테고리의 다른 글

타입스크립트 제네릭 제한  (0) 2025.02.26
🍖 타입스크립트 제네릭  (0) 2025.02.07
🦶 타입스크립트 인터페이스  (0) 2025.01.12
🧆 타입스크립트 기본 타입  (0) 2025.01.03
🧁 인터페이스  (1) 2024.11.17

댓글