function add(num1: number, num2: number): number{
return num1 + num2;
}
true
, false
면 boolean
이겠지요~?function add(num1: number, num2: number): void{
console.log(num1 + num2);
}
매개변수로 받을 값의 타입도 명시해야 한다!
리턴하는 값의 타입도 명시해야 한다!
리턴을 하지 않는다면void
!
function hello(name: string){
return `Hello, ${name} || "world"}`
}
const result = hello();
const result2 = hello("Joonyoung");
이렇게 하면 하나의 매개변수가 필요하다는 에러가 뜰 것이다.
name
이 없을 때를 대비한 코드가 있지만, 타입스크립트에서는 보다 명시적으로 알려줘야한다.
function hello(name?: string){
return `Hello, ${name} || "world"}`
}
const result = hello();
const result2 = hello("Joonyoung");
function hello(name = "world"){
return `Hello, ${name} || "world"}`
}
const result = hello();
const result2 = hello("Joonyoung");
function hello(age?: number, name: string): string {
if(age !== undefined){
return `Hello, ${name}. You are ${age}.`';
} else {
return `Hello, ${name}.`;
}
}
console.log(hello(27, "Joonyoung"));
console.log(hello(("Jonyoung"));
매개변수의 자리를 위와 같이 주게 된다면, 에러가 발생 할 것이다. (즉 선택적 매개 변수와 필수 매개보다 앞에오는 경우)
옵셔널의 값은 입력을 안해도 되는 것이기 때문에 위와 같은 코드는 성립이 불가능하다.
function hello(name: string, age?: number): string {
if(age !== undefined){
return `Hello, ${name}. You are ${age}.`';
} else {
return `Hello, ${name}.`;
}
}
console.log(hello("Joonyoung", 27));
console.log(hello(("Jonyoung"));
age
를 첫번째 매개변수로 주고 싶다면..function hello(age: number | undefined, name: string): string {
if(age !== undefined){
return `Hello, ${name}. You are ${age}.`';
} else {
return `Hello, ${name}.`;
}
}
console.log(hello(27, "Joonyoung"));
console.log(hello((undefined, "Jonyoung"));
age의 타입을 위와 같이 줄 수 있다.
number와 undefined를 받을수 있게 두고, 명시적으로 Undefined를 전달하는 방식으로 사용해야 한다.
function add(...nums: number[]){
return nums.reduce((result, num) => result + num, 0);
}
add(1, 2, 3); // 6
add (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // 55
...
를 사용하면 전달받은 매개변수를 배열로 나타낼 수 있게 하기 때문에 배열로 타입을 선언해야 한다.
따라서 number[]
=> number
가 들어간 array
타입이 되는 것이다.
interface User {
name: string;
}
const Joonyoung: User = {
name: "Joonyoung",
}
function showName(){
console.log(this.name);
}
const a = showName.bind(Joonyoung);
a(); // "Joonyoung"
위의 코드는 bind
를 이용해서 this
를 Joonyoung
객체로 강제하고 있다.
하지만 this의 타입이 정해지지 않아서 타입스크립트 에러가 날 것이다.
this
의 타입을 지정해보자
interface User {
name: string;
}
const Joonyoung: User = {
name: "Joonyoung",
}
function showName(this: User){
console.log(this.name);
}
const a = showName.bind(Joonyoung);
a(); // "Joonyoung"
interface User {
name: string;
}
const Joonyoung: User = {
name: "Joonyoung",
}
function showName(this: User, age:number, gender: "m" | "f"){
console.log(this.name, age, gender);
}
const a = showName.bind(Joonyoung);
a(30, 'm'); // "Joonyoung", 30, "m"
이렇게 this
다음부터 첫번쨰 두번째 순서대로 적용이된다. (this
를 제외하고 생각하면 편함)
interface User {
name: string;
age: number;
}
function join(name: string, age: number, | string): User | string {
if(typeof age === "number"){
return {
name,
age,
}
} else {
return "나이를 숫자로 입력하세요"
}
}
const joonyoung: User = join("Joonyoung", 27);
const aimzero: User = join("Aimzero", "27");
join
함수는 age
의 타입에 따라서 리턴하는 결과물의 타입도 달라지는 함수이다. (객체나 문자열을 리턴)
코드상에는 문제가 없어보이지만, const joonyoung
과 aimzero
에서 에러가 생길 것이다.
User
객체를 반환하는데 확신이 없어서 그런것이다. string
을 반환 할 수도 있다고 판단하는 것이다.
따라서 join
함수 내부에는 분명히 분기 처리를 했지만, 타입들만 보았을 때는 그렇지 않다는 것이다.
이럴때는 오버로드를 사용해야한다.
🙋🏻♂️ 함수 오버로드는 전달받은 매개변수의 개수나 타입에 따라 다른 동작을 하게 하는 것을 의미한다.
아래의 코드와 같이 함수 위에 똑같은 형태로 작성해주면, 확실하게 동작의 분기(?)를 나누는 것을 명시 할 수 있다.
interface User {
name: string;
age: number;
}
function join(name: string, age: string): string;
function join(name: string, age: number): User;
function join(name: string, age: number, | string): User | string {
if(typeof age === "number"){
return {
name,
age,
}
} else {
return "나이를 숫자로 입력하세요"
}
}
const joonyoung: User = join("Joonyoung", 27);
const aimzero: User = join("Aimzero", "27");
동일한 함수지만, 매개변수의 타입이나 개수에 따라 다른 방식으로 동작해야 된다면 오버로드를 사용 할 수 있다.