function sendGreeting(message, userName):void {}
function sendGreeting(message: string, userName?: string): void {
console.log(`${message}, ${userName}`);
}
sendGreeting("hello"); // hello, undefined
이렇게 선택적 매개변수로 지정하여 매개변수의 수가 일치하지 않아도 오류가 발생하지 않게 할 수 있다.
기본 매개변수
function sendGreeting(message: string, userName: string = "there"): void {
console.log(`${message}, ${userName}`);
}
sendGreeting("hello"); // hello, there
이렇게 기본 매개변수를 설정하게 되면 선택적 매개변수로 설정하지 않아도 there이 기본적으로 출력되게 되고, 이 때 string으로 지정해주지 않아도 된다. 타입스크립트는 타입추론이 가능하기 때문에!
const sendGreeting = ( message:string, userName:string = "there"):void => {
console.log(`${message}, ${userName}`)
}