前端学习TS之路——6(接口规定)

1.属性接口:对json的约束

function funname(laber:string):void{
	console.log(1)
}
funname('string')

TS中自定义方法传入参数对JSON进行约束

function funname(laber:{'label':string}):void{
	console.log(1)
}
funname({lable:'1224'})

接口:行为和动作的规范,对批量方法进行约束——interface

interface fullName{
	firstName:string;//分号结束
	secondName:string;
}
function funname(name: fullName){
//必须传入对象
}
printName({//直接传入时只能传入interface所定义的
	firstName:'222',
	secondName:'222'
})

先定义的话 可以只是包含interface所需的 可以增加别的属性

let obj = {
 	aa:'asdad'
	firstName:'222',
	secondName:'222'
}
printName(obj)

接口:可选属性

interface fullName{
	firstName:string;
	lastName?:string;
}
function getName(name:fullName){

}

getName({
	firstName:'ss';
})

实例:

interface Config{
	type:string;
	url:string;
	data?:string;
	datatype:string;
}
function ajax(config:Config){
	let xhr = new XMLHttpRepuest();
	xhr.open('get',config.type,config.url,true);
	xhr.send(config.data);
	xhr.onreadystatechange=function(){
	if(xhr.readyState==4&&xhr.status==200){
		console.log('200')
			if(config.dataType=='json'){
				JSON.parse(xhr.responseText)
			}else{
				console.log(xhr.responseText)
			}
		}
	}
}
ajax({
	type:'get',
	url:'http://www.baidu.com',
	dataType:'json'
})

函数类型接口:对方法传入的参数 以及返回值进行约束

加密的函数类型接口:

interface encrypt {
	(key:string,value:string):string;
	}
	let md5:encrypt = function(key:string,value:string):string{
	return key + value;
}
md5('name','pipi')

可索引接口:数组、对象的约束(不常用)

interface UserArr{
	[index:number]:string
}
let arr:UserArr= ['a','b']

interface Userobj{
	[index:string]:string
}
let obj:UserObj = {
	name:'adsasd'
}

类类型接口:对类的约束

interface Animal{
	name:string;
	eat(str:string):void;
}
class Dog implements Animal{
	name:string;
	constructor(name:string){
	this.name = name
	}
	eat(){
		console.log(1)
	}
}
let d = new Dog('asd')

接口的扩展:接口可以继承接口

interface Animal{
	eat():void;
}
interface Person extends Animal{
	work():void;
}
class Web implements Person{
	public name:string;
	constructor(name:string){
		this.name = name
	}
	eat(){
		console.log(1)
	}
	work(){
		console.log(2)
	}
}
let w= new Web('asd')
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值