这是我参与8月更文挑战的第19天,活动详情查看:8月更文挑战
接口声明
在 typescript 中,使用 interface 可以声明一个接口:
// 定义接口
interface Person {
}
所谓 typescript,就是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法
没使用接口实现的简单示例
function printInfo(infoObj: { name: string }) {
console.log(infoObj.name)
}
let datas = { name: '张三', age: 20 };
printInfo(datas);
使用接口实现必须包含一个 name 属性且类型为 string
interface typeValue {
name: string
}
function printInfo(infoObj: typeValue) {
console.log(infoObj.name)
}
let datas = { name: '张三', age: 20 };
printInfo(datas);
类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以,如:
interface infoValue {
age: number,
name: '张三'
}
可选属性
在开发过程中,有时候有些属性不是必须要传值的,只需要使用函数里预定义的默认值就行了,这时候就引出了可选属性
interface typeValue {
name?: string,
age?: number,
sex?: string
}
function printInfo(infoObj: typeValue) {
let newInfo = { name: '张三', sex: '中性' };
if (infoObj.name) {
newInfo.name = infoObj.name;
}
if (infoObj.sex) {
newInfo.sex = infoObj.sex;
}
console.log(newInfo);
}
let datas = { name: '李四' };
printInfo(datas);
可选属性定义只在可选属性名字定义的后面加一个?符号
只读属性
有些属性从定义后开始就不能改变值,这时候就可以使用只读属性来定义
interface typeValue {
readonly name: string,
age: number
}
let info: typeValue = { name: '张三', age: 20 };
typeValue.name = '李四'; // Cannot assign to 'name' because it is a read-only property.
只读属性定义只在只读属性名字的前面加一个 readonly
readonly vs const
判断该用 readonly 还是 const 的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用 readonly
函数类型
接口还可以描述函数类型
interface SearchFunc {
( source: string, subString: string ): boolean;
}
如何创建一个函数类型的变量,并将一个同类型的函数赋值给这个变量
let mySearch: SearchFunc;
mySearch = function( source: string, subString: string ) {
let result = source.search(subString);
return result > -1;
}
函数的参数名可以不用与接口里定义的名字相匹配
let mySearch: SearchFunc;
mySearch = function( src: string, sub: string ): boolean {
let result = src.search(sub);
return result > -1;
}
欢迎关注我的公众号:A纲 Coder,获得日常干货推送。最后再次感谢您的阅读,我是程序猿憨憨