函数
// 定义函数
const fn = function(a:string,b:number):string{
return a+b
}
let c = fn('tc',33) //tc33
// 若少一个参数,则有两种方式
//1.
const fn = function(a:string,b:number = 30):string{
return a
}
let c = fn('tc') //tc30
//2.
const fn = function(a:string,b?:number):string{
return a
}
let c = fn('tc')//tcundefined
//通过接口定义返回值
interface Person {
name:string,
age:number
}
const fn = function(user:Person):Person{
return user
}
let t = fn({
name:'tc',
age:30
})
console.log(t) //{name:'tc',age:30}
函数重载
//重载是方法名字相同,参数不同,返回类型可以相同也可以不同
//若参数类型不同,则参数类型设置为 any,否则报错
//参数数量不同,将不同的参数设置为可选,否报错
function fn(p: number): void
function fn(p: string, p1: number): void
function fn(p: any, p1?: any): void {
console.log(p)
console.log(p1)
}
let t = fn(1) //1,undefined
let c = fn('12',34) //'12',34
联合类型
//若 定义一个变量,要支持不同的类型,则用联合类型
let t:string | number = 't'
let t:string | number = 30
//以上均可
//工具函数来处理1,0对应true,false
let fn = function(type:number| boolean):boolean{
return !!type //加!!作为强制转换true false
}
let t = fn(0) //false
let c = fn(1) //true
let y = fn(false) //false
let k = fn(true) //true
交叉类型
// 两个类型合并成一个,类似于extands
interface Person {
name: string,
age: number
}
interface Man{
sex: string
}
const tc = (man: People & Man) => {
console.log(man.name)
console.log(man.age)
console.log(man.sex)
}
tc({'tc',age: 30,sex: 'man'});
类型断言
//格式: 值 as 类型 比如:num as string 或者<string>num
let fn = function(num:number | string){
return num.length //会报错,改成:(num as string).length
}
let t = fn('123') // 3