const a = (a: number, b: number) => {
return a * b;
}
a(1) //2개의 인수가 필요한데 1개를 가져왔습니다.
const b = (a: number, b?: number, c?: number)=>{
//매개변수 3개가 모두 주어졌을 경우
if(a && b && c){
return a * b * c;
}
return ('false');
}
console.log(b(1,2,3)); // 6
console.log(b(5)); // false
const c = (a: number, b = 0, c = 0)=>{
if(a && b && c){
return a * b * c;
}
return ('false');
}
console.log(c(1,2,3)); // 6
console.log(c(5)); // false
const d = (...nums: number[]) => {
return nums.reduce((acc, cur) => {
return acc * cur;
}, 1)
}
console.log(d(1,2,3,4,5)); // 120
//func 매개변수를 그대로 반환하는 함수
type Copy = {
<T>(array: T[], func: (e: T) => T): T[]
}
const newAry: Copy = (array, func) =>{
const result = [];
for(let i = 0; i < array.length; i++){
result.push(func(array[i]));
}
return result;
}
//T가 number로 한정됨
const e = newAry([1, 2, 3], (e) => e); //const newAry: <number>(array: number[], func: (e: number) => number) => number[]
//T가 string으로 한정됨
const f = newAry(['1', '2', '3'], (e) => e); //const newAry: <string>(array: string[], func: (e: string) => string) => string[]
type Copy = {
<T>(array: T[], func: (e: T) => T): T[]
}
const newAry: Copy = (array, func) =>{
const result = [];
for(let i = 0; i < array.length; i++){
result.push(func(array[i]));
}
return result;
}
//T가 number로 한정됨
const e = newAry([1, 2, 3], (e) => e); //const newAry: <number>(array: number[], func: (e: number) => number) => number[]
type Copy<T> = {
(array: T[], func: (e: T) => T): T[]
}
//T가 number로 한정됨
const newAry: Copy<number> = (array, func) =>{
const result = [];
for(let i = 0; i < array.length; i++){
result.push(func(array[i]));
}
return result;
}
const e = newAry([1, 2, 3], (e) => e); //const newAry: <number>(array: number[], func: (e: number) => number) => number[]
출처
보리스 체르니, 타입스크립트 프로그래밍(2021)