先端学習TSの道——6(インタフェース規定)

17398 ワード

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

先に定義すればインターフェースを含めるだけで他の属性を増やすことができます
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')