alswlfl 2023. 1. 3. 14:54

ํ•จ์ˆ˜ ํ˜•ํƒœ

function add(num1:number, num2:number){
  return num1+num2;
}
function isAdult(age:number):boolean{
  return age>10;
}
  • ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋„ optional๋กœ ์ง€์ • ๊ฐ€๋Šฅ(๋‹จ, ํƒ€์ž… ๋ช…ํ™•ํ•˜๊ฒŒ ๋ช…์‹œํ•ด์ฃผ์–ด์•ผ ํ•จ)
function hello(name?:string){
  return `Hello, ${name || "world"}`;
}
const result=hello();
const result2=hello("Sam");

//์ฃผ์˜์ : optional์ธ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ๋’ค์— ๋ฐฐ์น˜ํ•ด์•ผ ํ•จ
function hello2(name:string, age?:number):string{
  if(age!==undefined){
    return `Hello, ${name}. You are ${age}.`;
  }else{
    return `Hello, ${name}`;
  }
}
//๋งŒ์•ฝ optional์„ ์•ž์— ๋ฐฐ์น˜ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด
function hello3(age:number | undefined, name:string):string{
  if(age!==undefined){
    return `Hello, ${name}. You are ${age}.`;
  }else{
    return `Hello, ${name}`
  }
}
  • restํŒŒ๋ผ๋ฏธํ„ฐ(๋‚˜๋จธ์ง€ ๋งค๊ฐœ๋ณ€์ˆ˜: ๊ฐœ์ˆ˜๊ฐ€ ๋งค๋ฒˆ ๋ฐ”๋€” ์ˆ˜ ์žˆ์Œ) 
    • ์  ์„ธ ๊ฐœ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด, ์ „๋‹ฌ๋ฐ›์€ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐฐ์—ด๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Œ(์ฆ‰, ํƒ€์ž…์€ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ)
function add2(...nums:number[]){
  return nums.reduce((result,num)=>result+num,0);
}
add2(1,2,3);
add2(1,2,3,4,5,6,7,8,9,10);
  • this
interface User{
  name: string;
}
const Sam:User={name:'Sam'}

function showName(this:User){
  console.log(this.name)
}

const a=showName.bind(Sam);
a();
  • ์˜ค๋ฒ„๋กœ๋“œ: ์ „๋‹ฌ๋ฐ›์€ ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ๊ฐœ์ˆ˜๋‚˜ ํƒ€์ž…์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ๋™์ž‘์„ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ๊ฒƒ
    • ํ˜•ํƒœ๋ฅผ ์œ„์— ๋˜‘๊ฐ™์ด ์ ์–ด์ฃผ๋ฉด ๋จ
interface User2{
  name2:string;
  age2:number;
}

function join(name2: string, age2: string):string;
function join(name2: string, age2: number):User2;
function join(name2:string, age2:number | string):User2 | string{
  if(typeof age2==="number"){
    return{
      name2,
      age2,
    };
  }else{
    return "๋‚˜์ด๋Š” ์ˆซ์ž๋กœ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.";
  }
}