admin管理员组

文章数量:1636911

TypeScript:接口 interface

  • 一、接口
    • 类型别名 type
    • 接口 interface
  • 二、接口与类 implement

一、接口

类型别名 type

// 描述一个对象类型
type MyUserName=string|number;
let myname:MyUserName="abc";

type myType={
	name:string,
	age:number
}
const obj:myType={
	name:"Tony",
	age":18
}

接口 interface

接口就是用来定义一个类的结构,用来定义一个类中应该包含哪些属性和方法,同时接口也可以当成声明类型来使用。
可以重复定义。

interface myInterface{
	name:string,
	age:number
}
interface myInterface{
	gender:string,
}
const obj:myInterface={
	name:"Tony",
	age":18,
	gender:"男“”
}

二、接口与类 implement

接口可以在定义类的时候去限制类的结构。
接口中所有的属性不能有实际的值,所有的方法不能有方法体,是抽象方法;接口只定义对象的结构,不考虑实际值。

interface myInterface{
	name:string,
	sayHello():void;
}
// 定义类时,可以使类去实现一个接口,就是使类满足接口的要求
class myClass implements myInterface{
	name:string;
	sayHello(name){
		this.name = name;
	}
}

本文标签: 接口typescriptimplementInterface