TypeScript_2 对象数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 在typescript中,定义对象需要使用关键字interface(接口)
// 通过在接口定义约束,让数据结果满足约束的格式
interface Person {
name: string
}

// 对象的属性必须与接口一致
const person: Person = {
name: "xin"
}

// 重名的interface可以合并
interface data { name: String }
interface data { age: number }

let x: data = { name: "shunxin", age: 1 }
console.log(x); //{ name: 'shunxin', age: 1 }

//可选属性 使用? 可选属性也就是该属性不存在也可以编译
// 实则就算不用 ? 也可以忽略该属性
interface Person1 {
name: string,
age?: number
}
const person1: Person1 = {
name: "xin"
}
console.log(person1); //{ name: 'xin' }

// 任意属性[propName: string]
//如果定义了该属性,那么确定属性和可选属性都必须是该属性的子集
interface Person2 {
name: string,
age?: number,
[propName: string]: any
}

const person2: Person2 = {
name: "xin",
age: 1,
email: "123@qq.com"
}
console.log(person2); //{ name: 'xin', age: 1, email: '123@qq.com' }

// 只读属性 readonly 只读属性是不允许对象实例化之后再被赋值,只能读取
//实则无影响
interface Person3 {
name: string,
readonly age?: number,
[propName: string]: any,
}
const person3: Person3 = {
name: "xin",
age: 1,
}
person3.age = 123; //Cannot assign to 'age' because it is a read-only property.
console.log(person3); //{ name: 'xin', age: 123 }


// 添加函数
interface Person4 {
name: string,
readonly age?: number,
[propName: string]: any,
getName: () => void
}

const person4: Person4 = {
name: "xin",
age: 1,
getName: () => {
console.log(person4.name); //访问到对象的属性
},
}
person4.getName() //xin