ํ๋ก ํธ์๋/TypeScript
ํจ์
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 "๋์ด๋ ์ซ์๋ก ์
๋ ฅํด์ฃผ์ธ์.";
}
}