含义:接口(Interface)用于描述一个对象的结构或者一个类应该具备的属性和方法,它定义了对象的形状和行为
格式:
interface person {//定义一个接口person,包含了name,age,sex,id为只读,work是可写可不写,后续不可修改属性
name: string
age: number
sex: string
readonly id: number//只能读,使用点语法不能修改
readonly work?: string//在创建对象时可写可不写,写了使用点语法修改不了
}
let peple: person//将peple连接接口person
peple = { name: "jack", age: 12, sex: "男", id: 1234 }
接口中还可以包含接口
例:
interface person {//定义一个接口person,包含了name,age,sex属性
name: string
age: number
sex: string
readonly id: number//只能读,使用点语法不能修改
readonly work?: string//在创建对象时可写可不写,写了使用点语法修改不了
}
interface cat {
catowner: person//catown属性为person
catname: string
catage: number
catcolor: string
}
let people: person//将peple连接接口cat,若打印出来则出来cat本身的属性外,还有person接口中的属性
people = { name: "jack", age: 12, sex: "男", id: 1234 }
let cat1: cat//将cat1连接接口cat,若打印出来则出来cat本身的属性外,还有person接口中的属性
cat1 = { catowner: people, catname: "big", catage: 2, catcolor: "red" }
console.log(cat1)