typescript 函数

1.在 TypeScript 中创建函数的语法是相同的,除了一个主要的补充:我们可以让编译器知道每个参数或参数应该具有什么类型。

function printIn(age: number):number{
	console.log("年龄" + age)
}
printIn(22)
//年龄22

函数添加指定返回值的类型:(number)

function sum(a: number, b: number): number {
  return a + b;
}

对象类型函数传参数:

function initId(obj:{age: number,weight: string}){
	console.log("年龄" + obj.age + "体重" + obj.weight)
}
initId({age:24,weight:"150"})
//年龄24体重150

函数联合类型:

function printID(id :string | number | string[]){
	if(Array.isArray(id)){ //Array.isArray 判断是否为数组
		console.log(id.join("and"))
	}else if(typeof id === "string"){//对类型单独判断 typeof
		console.log("Your Id is" + id.toUpperCase()); 
	}else{
		console.log("Your Id is " + id) 
	}
}
printID("AAA");//Your Id isAAA
printID(222);//Your Id is222
printID(["a1","b2","c3"]);//a1andb2andc3

类型别名和类型继承:

//声明多个类型
type ID = string | number;
function idCard(name :ID){
	console.log(name)
}
idCard(222);//222
idCard("小王");//小王
//对象声明多个类型
type Point = {
	x: number,
	y: string
}
type Pointer = Point &{
	z:boolean
}//类型扩展 交叉类型
function PointCood(id :Pointer){
	console.log(id)
}
PointCood({x:22,y:"小王",z:true})//{ x: 22, y: '小王', z: true }

接口和接口继承:(现有类型追加字段)

//--------接口继承
interface Animal{
	name:number
}
interface Bear extends Animal{
	honey:string
}//接口扩展(继承)
const bear: Bear ={
	name:123,
	honey:"蜂蜜"
}
console.log(bear.name)//123
console.log(bear.honey)//蜂蜜
//============================
//------现有类型追加字段 (重复命名可追加字段)
interface Animal{
	name:string
}
interface Animal{
	age:number
}
const w: Animal ={
	name:"小王",
	honey:123
}
console.log(w.name)//小王
console.log(w.honey)//123

一.总结类型别名和接口的区别:
1.interface 可以声明合并,但是type无法定义,用type会报错 如果你多次声明一个同名的接口,TypeScript 会将它们合并到一个声明中,并将它们视为一个接口。这称为声明合并
2.type:创建类型别名,不仅可以用来表示基本类型,还可以表示对象类型,联合类型,元组和交集。但是interface无法定义
3.接口是命名数据结构的另一种方法;与Type不同,Interface仅限于描述对象类型

二.总结类型别名和接口的相同之处:
1.都可以描述Object 和Function,但语法不同
2.interface 和 type 都可以继承。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值