接口和对象类型
ts的interface跟Java的接口interface是一样的:
interface 重合,interface 任意key
typescript
interface Axxsxs{
name:string
age:number
[propName:string]:any//任意key,写上这个,继承此接口的对象就可以随意添加属性
}
interface Axxsxs{
Ikun:string
}
// interface 重合
let a:Axxsxs={
name: 'cxk',
age: 30,
Ikun: "Ikun",
a:123,
b:'ahhh'
}
interface ? readonly
typescript
interface Axxsxs{
name:string
age:number
readonly id:number // readonly使这个属性为只读属性,不可修改
readonly cb:()=>boolean// 一般会用于函数,id等
}
interface Axxsxs{
Ikun?:string//?使得继承此接口的对象可以不定义这个属性,
}
let a:Axxsxs={
name: 'cxk',
age: 30,
cb: () => {
return false
},
id: 0
}
a.cb()//可以读取
a.id=2//无法为“id”赋值,因为它是只读属性
interface 接口继承
typescript
// 继承B
interface Axxsxs extends B{
name: string
age: number
}
interface B {
Ikun: string
}
let a: Axxsxs = {
name: 'cxk',
age: 30,
Ikun:'Ikun'
}
interface 定义函数类型
typescript
interface Fn {
(name: string): number[]
}
//注意参数name的类型只能为string
const fn: Fn = function (name: string) {
return [1]
}
不能多属性,也不能少属性
typescript
interface Axxsxs{
name:string
age:number
}
interface Axxsxs{
Ikun:string
}
// 继承多个接口
let a:Axxsxs={
name: 'rarrot',
age: 0,
Ikun: "Ikun"
}