如何检查 TypeScript 中的接口类型?
Typescript 是一种纯面向对象的编程语言,由类、接口、继承等组成。它是严格的,并且像Java一样静态类型化。接口用于在 typescript 中定义联系人。通常,它定义了实体的规范。下面是汽车接口或合约的示例。
interface Audi {
length: number;
width: number;
wheelbase: number;
price:number;
numberOfAirBags:number;
seatingCapacity: number;
getTyrePressure: () => number;
}
方法:
- 用一个名称和它的类型作为一个字符串声明一个接口。
- 现在创建一个自定义函数来检查接口类型。
- 如果传递的参数中存在名称属性,则此函数返回一个布尔值。
- 现在使用 if 语句检查函数返回的值,并可以根据需求执行进一步的操作。
示例 1:
Javascript
interface Student{
name:string;
}
var geek:any = {
name: "Jairam"
};
function instanceOfStudent(data: any): data is Student {
return 'name' in data;
}
if (instanceOfStudent(geek)) {
document.write("Student Name is "+ geek.name);
}
Javascript
interface Bike{
companyName:string;
bikeNumber:any;
modelNo:any;
}
var bike:any = {
companyName: "Engfield"
};
function createName(name:any){
alert(name);
}
if(instanceOfBike(bike)) {
createName(bike.companyName)
}
else{
createName("No Name is registered with that company name")
}
function instanceOfBike(data: any): data is Bike {
return 'companyName' in data;
}
输出:
示例 2:
Javascript
interface Bike{
companyName:string;
bikeNumber:any;
modelNo:any;
}
var bike:any = {
companyName: "Engfield"
};
function createName(name:any){
alert(name);
}
if(instanceOfBike(bike)) {
createName(bike.companyName)
}
else{
createName("No Name is registered with that company name")
}
function instanceOfBike(data: any): data is Bike {
return 'companyName' in data;
}
输出: