区别
类型别名和 接口类似,但最关键的区别还是在于 接口可以通过集成扩展,而别名确定后无法添加新的属性,只能通过并集类型去扩展
接口的定义
//声明类型的两种方式
//通过type定义
// type InfoType = {name:string,age:number}
//通过intetface接口定义 可以定义可读属性 以及可选属性
interface InfoType{
name?:string
readonly age:number
}
const info:InfoType = {
name:'why',
age:18
}
interface LabelValue{
label:string
}
let myObj = { size: 10, label: '123' };
function printLabel(labelObj: LabelValue) {
console.log(labelObj.label);
}
printLabel(myObj);
索引类型和额外属性
//通过interface 定义索引类型
interface IndexLanguage{
[index:number]:string|number
}
const frontLanguage:IndexLanguage = {
0:"HTML",
1:"abc" //索引必须number
}
interface ILanguageYear{
[index:string]:number
}
const languageYear:ILanguageYear = {
"C":1972,
"Java":1995,
"Javascript":1996
}
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
let newObj: SquareConfig = {
color: "123",
abc: 456,
};
函数类型接口
interface Fc{
(source:string,subString:string):boolean
}
//接口函数相当于是函数的一个签名
//只要参数数量和类型一致,甚至类型都可以不写有类型推导
let mySearch:Fc = function(src:string,sub:string):boolean{
let result = src.search(sub)
return result > -1
}
接口的继承
//接口的继承
interface ISwim{
swimming:()=>void
}
interface IFly{
flying:()=>void
}
//多继承
interface IAction extends ISwim,IFly{
}
const action:IAction = {
swimming(){
},
flying(){
}
}
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
let squre = {
color: "blue",
sideLength: 10,
penWidth: 5.0,
} as Square;
交叉类型
interface ISwim{
swimming:()=>void
}
interface IFly{
flying:() => void
}
//联合类型 有其中一个就行
type myType1 = ISwim | IFly
//交叉类型 必须都有
type myType2 = ISwim & IFly
const obj1:myType1 = {
flying(){
}
}
const obj2:myType2 = {
flying(){
},
swimming(){
}
}
面向接口实现
interface IEat{
eating:()=>void
}
interface Swim{
Swiming:()=>void
}
//类实现接口
class Animal{
}
//继承只能单继承
//实现接口可以多个
class Fish extends Animal implements IEat,Swim{
eating(){
}
Swiming(){
}
}
class Person extends Animal implements Swim{
Swiming(){
}
}
//实现场景 一些公共的API 面向接口编程
//通过类来实现接口的 方法
function swimAction(swimable:Swim){
swimable.Swiming()
}
//所有实现了Swim接口的类对应的对象 都是可传入的
swimAction(new Fish())
swimAction(new Person())