typescript

๐Ÿง ์ธํ„ฐํŽ˜์ด์Šค

frontChoi 2024. 11. 17. 20:18
๋ฐ˜์‘ํ˜•

 

๐Ÿซ˜ ์ธํ„ฐํŽ˜์ด์Šค๋ž€

์ปดํ“จํ„ฐ์„ธ์ƒ์—์„œ์˜ ์ธํ„ฐํŽ˜์ด์Šค๋Š” ์ƒํ˜ธ๊ฐ„์˜ ๊ทœ์น™์ด๋ฉฐ, ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ํƒ€์ž…์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ์ƒˆ๋กœ์šด ํƒ€์ž….
์—ฌ๋Ÿฌ๊ฐ€์ง€์˜ ํ”„๋กœํผํ‹ฐ์™€ ๋ฉ”์†Œ๋“œ๋“ค๋กœ ์ด๋ฃจ์–ด์งˆ์ˆ˜ ์žˆ์Œ.  
ํด๋ž˜์Šค์™€ ์ฐจ์ด๋Š” ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜์ง€ ์•Š์Œ

 

โ˜•๏ธ ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ

name๊ณผ age๋ฅผ ๊ฐ€์ง„ PersonInterface๋ฅผ ์ƒ์„ฑํ•œ๋‹ค

person2๋ฅผ ๊ฐ€์ง€๋Š” ํ•จ์ˆ˜๋Š” PersonInterfaceํƒ€์ž…๋งŒ ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

๊ทธ๋ฆฌํ•˜์—ฌ personObject๋Š” name,age๋ฅผ ๊ฐ€์ง„ ๊ฐ์ฒด๋ฅผ person2ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.

์ด๋Ÿฌํ•œ ๋ฐฉ์‹์œผ๋กœ ๊ฐ์ฒด์˜ ํƒ€์ž…์„ ์ถ”๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค.

// ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
interface PersonInterface{
    name:string,
    age:number
}

function person2(person:PersonInterface){
    console.log(person.name,person.age);
}

const personObject = {
    name:"์ตœ๋Œ€๊ฑด",
    age:32
}

person2(personObject)

 

 

๐Ÿˆ ์ธํ„ฐํŽ˜์ด์Šค ์„ ํƒ์  ํ”„๋กœํผํ‹ฐ

๋ชจ๋“  ์ธํ„ฐํŽ˜์ด์Šค์˜ ํ”„๋กœํผํ‹ฐ๊ฐ€ ๊ผญ ํ•„์ˆ˜์ผ ํ•„์š”๋Š” ์—†๋‹ค. ํ•„์ˆ˜๊ฐ€ ์•„๋‹ ๊ฒฝ์šฐ๋Š” ?๋ฅผ ํ†ตํ•ด ์„ ํƒ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜  ์žˆ๋„๋ก ํ•œ๋‹ค.

//์„ ํƒ์ ํ”„๋กœํผํ‹ฐ
interface PersonInterface2{
    name?:string,
    age?:number
}

function person3(person:PersonInterface2): {fullName:String}{
    const newPerson = {
        fullName:""
    }
    if(person.name){
        newPerson.fullName += person.name
    }
    
    if(person.age){
        newPerson.fullName += "/"+person.age
    }
    return newPerson
}

person3({
    age:11
})

 

 

๐Ÿž ํ•จ์ˆ˜ ํƒ€์ž…

๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์•„๋‹Œ ํ•จ์ˆ˜๋„ ํƒ€์ž…์„ ์ •ํ• ์ˆ˜๊ฐ€ ์žˆ๋‹ค.

//ํ•จ์ˆ˜ํƒ€์ž…
interface SearchFunc{
    (source:string,subString:string):boolean
}
let mySearchFunc:SearchFunc
mySearchFunc = function(source:string,subString:string){
    let result = source.search(subString)
    return result > -1
}

// ํ•จ์ˆ˜ํƒ€์ž…2
interface searchFunc2{
    (num1:number,num2:number):boolean
}

const diffNumber:searchFunc2 =function(a,b){

    return a>b;
}

diffNumber(1,2)
๋ฐ˜์‘ํ˜•