타입스크립트 선택적 매개변수 예제
-
function 함수이름(필수값: 타입, 선택값?: 타입) {
// 실행 코드
}-
function greet(name: string, age?: number): string {
if (age === undefined) {
return `${name}님, 안녕하세요.`;
}
return `${name}님은 ${age}살입니다.`;
}
console.log(greet("민수"));
console.log(greet("지영", 25));-
function searchProducts(keyword: string, category?: string): string {
if (category) {
return `${category} 카테고리에서 ${keyword}를 검색합니다.`;
}
return `전체 상품에서 ${keyword}를 검색합니다.`;
}
console.log(searchProducts("노트북"));
console.log(searchProducts("노트북", "전자제품"));-
function printMessage(message?: string): void {
console.log(message);
}
printMessage("안녕하세요");
printMessage();-
function printMessage(message?: string): void {
if (message === undefined) {
console.log("기본 메시지입니다.");
return;
}
console.log(message);
}-
function createPost(title: string, content?: string) {
return {
title,
content: content ?? "내용 없음",
};
}-
function createPost(content?: string, title: string) {
// 오류 발생 가능
}-
댓글
댓글 쓰기