声明方式
interface直接通过关键字+名字+{}方式进行声明
interface Name { name:string }
type是通过关键字+名字+“=”+{}的方式进行声明
type Name = { name:string }
扩展接口
interface通过关键字extends来扩展
interface Animal { name:string } interface Bear extends Animal { honey:boolean } const bear:Bear = { name:'wine', honey:true } console.log(bear.name) // wine console.log(bear.honey) // true
type通过特殊符号&来进行扩展
type Animal = { name:string } type Bear = Animal & { honey:boolean } const bear:Bear = { name:'wine', honey:true } console.log(bear.name) // wine console.log(bear.honey) // true
向现有的类型中添加字段方式不同
interface通过多次声明的方式,来新增或者覆盖原有的字段
interface MyInfo { name:string } interface MyInfo { age:number } const M:MyInfo = { name:"mengxyz.com", age:18 }
通过type创建的类型,不能更改,不能进行多次重复命名进行修改