ts中自定义方法传入参数,对json进行约束
示例:
function printLabel(labelInfo: {
label: string }): void {
console.log("printLabel");
}
printLabel({
label: "张三" }); //正确的写法
接口
接口的作用:在面向对象的编程中,接口是一种规范的定义,
它定义了行为和动作的规范,在程序设计里面,
接口起到一种限制和规范的作用。接口定义了某一批类所需要遵守的规范,
接口不关心这些类的内部状态数据,也不关心这些类里方法的实现细节,
它只规定这批类里必须提供某些方法,提供这些方法的类就可以满足实际需要。
typescrip中的接口类似于java,同时还增加了更灵活的接口类型,包括属性、函数、可索引和类等。
定义标准。
属性接口
/*
属性接口
ts中自定义方法传入参数,对json进行约束
*/
function printLabel(labelInfo: {
label: string }): void {
console.log("printLabel");
}
printLabel({
label: "张三" }); //正确的写法
//接口:行为和动作的规范,对批量方法进行约束
interface FullName {
firstName: string; // 注意,约束
secondName: string;
}
function printName(name: FullName): void {
// 必须传入对象 firstName secondName
console.log(name.firstName + " : " + name.secondName);
}
// 直接传入对象,对象的属性必须严格对照接口,不能多也不能少
printName({
firstName: "张",
secondName: "三",
});
var obj = {
/*传入的参数必须包含 firstName secondName*/
age: 20,
firstName: "张",
secondName: "三",
};
printName(obj);
接口,可选参数
// 接口:可选属性
interface FullName02 {
firstName02: string;
secondName02?: string;
}
function getName(name: FullName02) {
console.log(name);
}
getName({
firstName02: "firstName",
});
ts接口完整ajax封装
/*
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json"
});
*/
int
interface Config{
type:string;
url:string;
data?:string;
dataType:string;
}
//原生js封装的ajax
function ajax(config:Config){
var xhr=new XMLHttpRequest();
xhr.open(config.type,config.url,true);
xhr.send(config.data);
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
console.log('chengong');
if(config.dataType=='json'){
console.log(JSON.parse(xhr.responseText));
}else{
console.log(xhr.responseText)
}
}
}
}
ajax({
type:'get',
data:'name=zhangsan',
url:'http://a.itying.com/api/productlist', //api
dataType:'json'
})