ts---学习类型--- interface篇

interface篇
定义:interface:接口,感觉像是自定义类型,因为ts中,会进行类型的强校验,但是除了基本数据类型,引用类型,还可以具体定义某一个对象的属性

使用:比如:

interface Person{
	name:string;
	age?:string;
}
这是接口类型,要求此类型必须有name属性,?表示可以有age属性,可以没有age属性。

同自定义类型的type的区别
如下,type类型可以直接代替某基础类型,但是interface接口不可以,接口一般都代表具体对象类型。

type Person1 ={
  name:string,
}
type Person2 = string;

ps:


const getPersonName = (person:Person):void=>{
  console.log(person.name)
}
const person = {
  name:'lee',
  sex:0,
}
// 此时直接调用getPersonName(person)和调用
getPersonName(
 {
  name:'lee',
  sex:0,
}
)
//不一样,后者会报错,因为如果不传变量,ts将会对传入的obj做强类型检测,这时,检测到interface接口中没有sex的变量,就会报错。但是传入person变量这种就没有问题

常用方式:接口和type都是ts用来帮助我们做类型校验的,在编译成js之后,根本没有这些东西

// 接口 
// 1.可以提供灵活的propName,来兼容之后的属性
interface Person {
// readonly name:string; // 只能读的属性
  name:string;
  age?:number; // ?代表可以有可以没有
  [propName:string]:any; // 属性是string类型,值是any类型
}
//2.可以有方法
interface Person {
  name:string;
  age?:number; // ?代表可以有可以没有
  [propName:string]:any;
  say():string;   // 返回值为string
}
// 3. class 类实现接口
class user implements Person{
  name='dell';
  say(){
    return 'hello';
  }
}
//4.接口继承接口
interface teacher extends Person{
  teach():string;
}
// 此时如果某个类是teacher类型,必须要有teach方法,否则就会报错
//5.接口定义方法
interface SayHi{
  (word:string):string
}
const sy:SayHi=(word:string)=>{return word}

版权声明:本文为weixin_44063886原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。