美文网首页web前端
TypeScript学习笔记之四接口(Inferfaces)

TypeScript学习笔记之四接口(Inferfaces)

作者: 摸着石头过河_崖边树 | 来源:发表于2018-12-10 15:11 被阅读37次

一、使用环境

  • Mac 电脑
  • WebStorm
  • TypeScript3.x版本

二、接口

在 TypeScript 中,我们使用接口(Interfaces)来定义对象的类型,在OOP编程中接口都是比较常见且重要的概念
接口的作用
A、对类的一部分行为进行抽象,详细情况见TypeScript学习笔记之五类(Class)最后
B、描述对象的形状

1、遵守协议的对象具有协议属性,但是不用完全是,接口里的属性不全都是必需的
interface LableValueInterface {
label : string;
name: string;
color ?:string;  //可选属性
}

function printLableValue(lableObject:LableValueInterface) {
 console.log(lableObject.label);
}
let  myobject = {label: '我是lzb你',name:"明智",age:"27"};  //Error
let  myobject = {label: '我是lzb你',name:"明智"};  //True
let  myobject = {label: '我是lzb你',name:"明智",color:"red"};  //true
printLableValue(myobject);

注意:

接口一般首字母大写, 也可以在接口之前加大写I
赋值的时候,变量的形状必须和接口的形状保持一致。
不允许添加未定义的属性

接口描述的属性必须和对象的一致,,就是是可选属性,但是也不允许添加未定义的属性,如果我有一种需求需要增加任意的属性是否有方法呢?

2.1 接口接受任意属性

使用 [propName : string] : any; //允许有任意的属性

interface IPerson{
readonly  id : number;  //只读属性
name : string;
age? : number;   //可选类型属性
[propName : string] : any;  //允许有任意的属性
 }
let tom : IPerson ={
 name :'Tom',
 tomee: "tomonni",
 age :23,
 id : 33444,
 };

注意:

一旦定义了任意属性,那么确定属性和可选属性都必须是它的子属性
只读的约束存在于第一次给对象赋值的时候,而不是第一次给只读属性赋值的时候

2.2 函数类型的接口
为了使用接口表示函数类型,我们需要给接口定义一个调用签名
//只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型
 interface SearchFunc {
(souce: string, substring: string) : boolean;
}
 let searchfunc : SearchFunc;
 searchfunc = function (souce: string, substring: string) : boolean {
  let result = souce.search(substring);
  return result> -1;
 }
2.3 可索引类型的接口

可索引类型具有一个 索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。

 //具有索引签名。 这个索引签名表示了当用 number去索引StringArray时会得到string类型的返回值。
interface StingInterface {
[index : number] : string;
}
let myArray : StingInterface;
myArray = ["sddad","45455"];
let mystr = myArray[0];

//TypeScript支持两种索引签名:字符串和数字
// 可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。
class Animal {
name : string;
}

class  Dog extends Animal{
age : string;
}
//同时使用number返回类型是string返回类型的子类
interface NotOkay {
[index : string] : Animal;
[index : number] : Dog;
}
2.4 类 类型接口
 interface ClockInterface {
currentTime : Date;
setTime(d : Date);
 }

 class Colck implements ClockInterface{
currentTime : Date;
setTime(d : Date){
  this.currentTime =  d;
}
// constructor存在于类的静态部分
constructor(h:number, m:number){};
 }

如需了解更多知识
TypeScript学习笔记之五类(Class)
TypeScript学习笔记之四接口(Inferfaces)
TypeScript学习笔记之三非原始数据类型
TypeScript学习笔记之二基本数据类型
TypeScript学习笔记之一初见TypeScript

相关文章

网友评论

    本文标题:TypeScript学习笔记之四接口(Inferfaces)

    本文链接:https://www.haomeiwen.com/subject/hkgrhqtx.html