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')