函數(shù)擴展
參數(shù)類型
//注意,參數(shù)不能多傳,也不能少傳 必須按照約定的類型來
const fn = (name: string , age : number ) : string => {
return name + age
}
let desc = fn( "張三", 18)
console.log(desc)
可選參數(shù)與默認值
//可選的參數(shù) 和 默認參數(shù)
const fn_002 = (name: string = "tom" , age? : number ) : string => {
return name + age
}
let desc_002 = fn_002( )
console.log(desc_002)
接口定義函數(shù)
interface Add {
//定義參數(shù) num 和 num2 :后面定義返回值的類型
( num : number , num2 : number ) : number
}
const fn_add : Add = (num : number , num2 : number ) : number =>{
return num + num2
}
fn_add( 5 , 5)
interface User {
name : string,
age ?: number
}
function getUserInfo(user : User) : User {
return user
}
let u001 = getUserInfo({
name : "五十" ,
age : 18
})
console.log(u001)
定義剩余參數(shù)
const fn_003 = (array : number[] , ...items : any[] ) : any[] =>{
console.log( "剩余參數(shù)", items )
return items
}
let num_list : number[] = [1,2,3]
fn_003( num_list, 4 , 5 , 6 )
函數(shù)重載
定義
函數(shù)重載是指在 TypeScript 中定義多個具有相同名稱但參數(shù)類型或參數(shù)數(shù)量不同的函數(shù)聲明。
函數(shù)重載規(guī)則
-
1, 多個函數(shù)定義使用相同的函數(shù)名稱
-
2, 函數(shù)參數(shù)的數(shù)量或類型必須有區(qū)別
-
3,如果參數(shù)類型不同, 則參數(shù)類型應設置為 any
-
4,返回類型可以相同也可以不同。
作用
通過使用函數(shù)重載,可以為同一個函數(shù)提供多個不同的函數(shù)簽名
,從而提供更嚴格的類型檢查和更清晰的函數(shù)使用方式。文章來源:http://www.zghlxwxcb.cn/news/detail-666833.html
常見報錯
文章來源地址http://www.zghlxwxcb.cn/news/detail-666833.html
到了這里,關于【005】ts學習筆記【函數(shù)擴展】的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!