1.给一个对象加类型注解
let person:{ name:string //?表示age这个属性可有可无 age?:number //方法的类型注解重点在于1.参数的类型 2.函数返回值的类型,如果没有返回值 这是void sayHi:() => void sing:(name:string)=>void sum:(num1:number,num2:number) => number } //给person赋值 person = { name:‘yogi‘, sayHi(){}, sing(name){ }, sum(num1,num2){ return num1+num2 } }
上面是给person这个对象加了注解,但是这个注解只能约束person这个对象,如果有多个对象都需要用相同的类型注解来约束呢?要给每个对象都加重复的类型注解吗?
2.接口
interface Person{ name:string //?表示age这个属性可有可无 age?:number //方法的类型注解重点在于1.参数的类型 2.函数返回值的类型,如果没有返回值 这是void sayHi:() => void sing:(name:string)=>void sum:(num1:number,num2:number) => number } let xiaoming:Person = { name:‘xiaoming‘, sayHi(){}, sing(name){ }, sum(num1,num2){ return num1+num2 } } let xiaofang:Person= { name:‘xiaofang‘, age:18, sayHi(){}, sing(name){ }, sum(num1,num2){ return num1+num2 } }
原文:https://www.cnblogs.com/BlueCc/p/14426130.html