一、概述
TypeScript中除了es5中的string、boolean、number、array、null和undefined之外还多了元组类型tuple、枚举类型enum、任意类型any、void类型、never类型,除此之外还有一种特殊的类型联合类型,学过Java的小伙伴应该并不陌生接口这个名词,今天小编带着大家认识下Typescript中的接口是什么样的,学完这个是不是都对后端的Java又有了更近一步认识,距离全栈开发又近了一步,如果大家觉得有帮助,记得给小编点个赞,如果想获取更多干货请关注前端微服务公众号,不定期为大家带来干货。
二、联合类型(Union Types)
联合类型(Union Types)可以通过管道(|)将变量设置多种类型,赋值时可以根据设置的类型来赋值(注意:只能赋值指定的类型,如果赋值其它类型就会报错)用一句话概括就是联合类型表示取值可以为多种类型中的一种。
三、创建联合类型的语法格式
Type1|Type2|Type3
四、使用案例
4.1 声明一个联合类型
/** * 联合类型 */ let type:string|number type = 12 console.log("数字为 "+ type) type = "xunzhaotech" console.log("字符串为 " + type) //错误代码 type = true console.log("布尔类型 " + type)
4.2 将联合类型作为函数参数使用
/** * 联合类型参数 */ function getName(name:string|string[]) { if(typeof name == "string") { console.log(name) } else { let i:number; for(i = 0;i<name.length;i++) { console.log(name[i]) } } } getName("xunzhaotech") console.log("输出数组参数....") getName(["张三","李四"])
4.3 联合类型数组
/** * 联合类型数组 */ let arr:number[]|string[]; let i:number; arr = [1,2,4] console.log("**数字数组**") for(i = 0;i<arr.length;i++) { console.log(arr[i]) } arr = ["张三","李四"] console.log("**字符串数组**") for(i = 0;i<arr.length;i++) { console.log(arr[i]) }
4.4 接口
关键词interface
来定义一个接口
interface Person { name: string } function getPerson(person:Person): void { console.log(person.name); } let obj = { age: 10, name: 'xunzhaotech' }; getPerson(obj); // xunzhaotech
4.4.1 可选属性
interface Person { name: string; age?: string; } function getPerson(person:Person): void { console.log(person.name); } let obj = { name: 'xunzhaotech' }; getPerson(obj); // xunzhaotech
4.4.2 只读属性
拥有只读属性不可改变它的值
interface Iperson { readonly name: string; age: number; } let obj: Person = { name: 'zunzhaotech', age: 29 }; obj.name = 'xunzhaotech' // error
4.4.3 函数类型
interface Person { (name: string, age: number): boolean; } let getPerson:Person = (name, age) => { return age > 20; } getPerson('xunzhaotech', 29)
4.4.4 常用的Object定义
interface Person { name: string; age?: number|string; } let list: Person[] = [ { name: '王麻子' }, { name: '张三', age: 29 }, { name: '李四', age: '29' } ]