对象的类型
在typescript中,我们定义对象的方式要用关键字interface(接口),我的理解是使用interface来定义一种约束,让数据的结构满足约束的格式。定义方式如下:
// 这样写会报错,使用接口约束的时候不能多一个属性也不能少一个属性
// 必须保证与接口一致
interface Person {
a: string,
b: string
}
const person: Person = {
a: '123'
}
// 重命名interface 可以合并
interface A {name: string}
interface A {age: number}
var x: A = {name: 'xx', age: 22}
// 继承
interface A {
name: string
}
interface B extends A {
age: number
}
let obj: B = {
age: 18,
name: '小小'
}
可选属性 使用?操作符
// 可选属性的含义是属性可以不存在
interface Person {
b?: string,
a: string,
}
const person: Person ={
a: '121'
}
任意属性 [propName: string]
需要注意的是,一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集:
// 在这个例子中我们看到接口中并没有定义c但并没有报错
// 因为我们定义了任意属性
interface Person {
b?: string,
a: string,
[propName: string]: any
}
const person: Person = {
a: '123',
c: '23'
}
只读属性 readonly
readonly 只读属性是不允许被赋值的只能读取
// 这样写会报错,因为a是只读的不允许重新赋值
interface Person {
b?: string,
readonly a: string,
[propName string]: any
}
const person: Person = {
a: '123',
c: '123'
}
person.a = 123
添加函数
interface Person {
b?: string,
readonly a: string,
[propName: string]: any;
cb:()=>void
}
const person: Person = {
a: '123',
c: '123'
cb: () => {
console.log('xxxx')
}
}