2.接口和对象类型
对象类型:在typescript中,我们定义对象的方式要用关键字interface(接口),我的理解是使用interface来定义一种约束,让数据的结构满足约束的格式。定义方式如下:
interface Person{
a:string;
b:string
}
//这样写是回报错的,因为在接口Person里已经定义了a,b,但是使用Person接口的对象却缺少b属性
const person:Person = {
a:"123"
}
//正确写法,使用了接口时,使用的对象里的属性必须跟接口一样,属性的类型也要保持一致
const person:Person = {
a:"123",
b:"999"
}
1.interface重名可以合并
interface A{
name:string
}
interface A{
age:number
}
const a:A = {
name:"fly",
age:20
}
2.interface继承
interface A{
name:string
}
interface B extends A{
age:number
}
const person:B = {
name:"fly",
age:18
}
3.可选属性
接口属性使用?操作符后,使用该接口的对象里的该属性可有可无
interface Person{
a:string;
b?:string;
}
const person1:Person = {
a:string
}
const person2:Person = {
a:string,
b:string
}
4.任意属性 [key:string]
interface Person{
a:string;
b:number;
[key:string]:any;
}
const person:Person = {
a:"111";
b:111;
c:"c";
d:false
}
5.只读属性readonly
有readonly的属性不允许被赋值,只能读取
interface Person{
name:number;
readonly age:number
}
const person:person = {
name:"fly",
age:22
}
//这样操作回报错
person.age = 18
6.添加函数
interface Person{
name:number;
age:number;
run:()=>void
}
const person:Person = {
name:"fly",
age:18,
run:()=>{
console.log("跑步")
}
}
7.定义函数类型
interface Fn {
(name:string):number[]
//这里表示函数的参数是name,类型是string,返回一个数组类型,数组元素是number类型
}
const fn:Fn = function(name:string){
return [1,2]
}