TypeScript #3 Function

2023. 3. 11. 02:04공부/TypeScript

function hello(name: string){
    return `Hello, ${name || "World!"}`
}
//타입스크립트는 명시적인것을 좋아한다.
//name이 없으면 World가 출력되어야 하는 코드지만..
//에러가 발생한다
const result = hello(); //hello()함수에는 argument가 필요하다.
//아래와 같이 name을 옵셔널로 주는것도 방법이다.
function hello(name?: string){
    return `Hello, ${name || "World!"}`
}

const result = hello();
const result = hello("kim");

 

매개변수의 순서도 중요하다.

선택적 매개변수는 필수매개변수의 뒤에 위치해야한다.

 

타입스크립트는 명시적인것을 매우 좋아한다.

 

 

타입스크립트에서 Rest 파라미터 표기법

//Rest Parameter표기법
function add(...nums: number[]){
    return nums.reduce((result, num)=> result + num, 0);
}

 

TypeScript에서 This의 사용법

interface User{
    name: string;
}

const Sam:User = {name:'Sam'}

function showName(this:User, age:number, gender:'m'|'f'){
    console.log(this.name, age, gender);
}

const a = showName.bind(Sam);
a(30,'m');

 

하나의 함수를 동작하려고하는데 전달받은 매개변수의 갯수나 타입이 다를 경우

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 sam: User = join("Sam", 30);
const jane:string = join("Jane", "33");

'공부 > TypeScript' 카테고리의 다른 글

TypeScript #7 Utility type  (0) 2023.03.14
TypeScript #6 Generic  (0) 2023.03.12
TypeScript #5 Class  (0) 2023.03.12
TypeScript #4 Literal/Union/Intersection types  (0) 2023.03.11
TypeScript #1 Type  (0) 2023.03.10