TypeScript:函数类型接口

接口也可以用于描述函数的形状,也就是描述函数的参数列表,以及返回值类型:

interface phoneCall{//定义一个打电话的函数类型接口,约定该函数需要有一个string类型的参数,然后返回值类型为void
	(phoneNumber : string):void;
};

let makePhoneCall: phoneCall;//定义一个phoneCall接口类型的变量

function iphone(phoneNumber : string):void{//定义通过iphone打电话的函数
	console.log("phone call to ", phoneNumber, "by iphone");
}

function android(number : string):void{//定义通过android打电话的函数
	console.log("phone call to ", number, "by android");
}

makePhoneCall = iphone;//将函数iphone赋值给函数类型的接口变量
makePhoneCall("12345");//通过函数类型接口函数调用函数,输出:phone call to  12345 by iphone
makePhoneCall = android;//将函数android赋值给函数类型的接口变量
makePhoneCall("67890");//通过函数类型接口函数调用函数,输出:phone call to  67890 by android

可以把对象类型接口与函数类型接口联合起来使用:

interface phoneCall{//定义函数类型接口
	(phoneNumber : string) : string;
};

interface Human{//定义对象类型接口,对象包含一个phoneCall类型的属性
	name : string,
	makePhoneCall : phoneCall
};

function humanMakeCall(data : Human, number: string)
{
	console.log(data.name, data.makePhoneCall(number));
}

function iphone(phoneNumber : string) : string{
	return "phone call to " + phoneNumber + " by iphone";
}

function android(number : string) : string{
	return "phone call to " + number + " by android";
}

let xiaoMing = {
	name : "XiaoMing",
	makePhoneCall : iphone
};

let xiaoHong = {
	name : "XiaoHong",
	makePhoneCall : android
};

humanMakeCall(xiaoMing, "12345");//输出:XiaoMing phone call to 12345 by iphone
humanMakeCall(xiaoHong, "67890");//输出:XiaoHong phone call to 67890 by android

你可能感兴趣的:(TypeScript,typescript,前端)