接口和对象类型
对象类型
声明与定义
1 2 3 4 5 6 7 8 9
| interface Person { name:string, age:number }
let person:Person = { name:'lwh', age:18 }
|
重名接口可合并
1 2 3 4 5 6 7 8 9 10 11
| interface Student { name:string } interface Student { age:number }
let student:Student = { name:'hwl', age:81 }
|
继承
1 2 3 4 5 6 7 8 9
| interface Pupil extends Student{ grade:number }
let pupil:Pupil = { name:'sb', age:11, grade:4 }
|
可选属性
1 2 3 4 5 6 7 8
| interface Choice { a:string, b?:number }
let choice:Choice = { a:'a' }
|
任意属性
可参考https://juejin.cn/post/6855449252785717256
如果需要一个接口需要有任意的属性签名,这时就会用到任意属性。
任意属性有两种定义的方式:一种属性签名是 string
类型的,另一种属性签名是 number
类型的。
string类型任意属性
1 2 3 4 5 6 7 8
| interface A { [prop:string]:any }
let aa:A = { a:'hello', b:114514 }
|
number类型任意属性
1 2 3 4 5 6 7 8 9 10 11 12
| interface B { [prop:number]:number }
let bb:B = { 1:22333, 2:114514, 100:99 }
console.log(bb[1]) console.log(bb[100])
|
输出
只读属性
1 2 3 4 5 6 7 8 9
| interface Read { a:number, readonly b:string }
let read:Read = { a:114514, b:'lwh' }
|
添加函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| interface Student { name:string } interface Student { age:number, score:number, exam():number }
let student:Student = { name:'hwl', age:81, score:90, exam(): number { this.score = this.score + 1; return this.score; } }
|