TypeScript (4)


📗 간단하게 알아보기

📍 반환되는 값이 number일 때..

function add(num1: number, num2: number): number{
		return num1 + num2;
}
  • 리턴값이 true, falseboolean이겠지요~?

📍 반환되는 값이 없을 때..

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이 없을 때를 대비한 코드가 있지만, 타입스크립트에서는 보다 명시적으로 알려줘야한다.

👇 다음과 같이 옵셔널로 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타입이 되는 것이다.


📗 this의 타입 선언 (feat. bind)

call, appy, bind를 알아보자..

interface User {
 name: string;
}
const Joonyoung: User = {
	name: "Joonyoung",
}
function showName(){
	console.log(this.name);
}
const a = showName.bind(Joonyoung);
a(); // "Joonyoung"

위의 코드는 bind를 이용해서 thisJoonyoung객체로 강제하고 있다.
하지만 this의 타입이 정해지지 않아서 타입스크립트 에러가 날 것이다.
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"

👇 매개변수가 여러개 있다면, 맨 첫번째 매개변수로 this의 타입을 지정하자

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를 제외하고 생각하면 편함)


📗 매개변수의 타입이나 개수에 따라 다른 방식으로 동작해야 된다면 (overLoading)

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 joonyoungaimzero에서 에러가 생길 것이다.

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");

동일한 함수지만, 매개변수의 타입이나 개수에 따라 다른 방식으로 동작해야 된다면 오버로드를 사용 할 수 있다.

profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글