文章目录
- 1.定义
- 2.TypeScript 类型模板
- 3.为对象动态添加属性
- 3.1 解决方法
- 3.2 对象作为参数传递
- 3.3 方法返回对象
- 3.4 对象数组
1.定义
TypeScript 对象是包含一组键值对的实例。 值可以是标量、函数、数组、对象等,如下实例:
| var object_name = { |
| key1: "value1", |
| key2: "value", |
| key3: function() { |
| |
| }, |
| key4:["content1", "content2"] |
| } |
| |
| |
| object_name.key1 |
| object_name.key4 |
复制
2.TypeScript 类型模板
| var sites = { |
| site1: "", |
| site2: 0, |
| sayHello: function () { } |
| }; |
| |
| sites.site1 = "site1" |
| sites.site2 = 2 |
| sites.sayHello = function () { |
| console.log("hello " + sites.site1 + sites.site2); |
| }; |
| |
| sites.sayHello(); |
复制
3.为对象动态添加属性
如果我们使用以上的方法定义对象是无法做到为对象动态添加属性
| let people = { |
| name: "hwm", |
| age: 18, |
| sayHello: ()=> {} |
| } |
| |
| people.sex = "man" |
复制
以上代码会报错:

3.1 解决方法
定义一个包含数组属性的接口,让对象实现该接口
| interface obj { |
| [idx: string]: any |
| } |
| |
| let people: obj = {} |
| people.name = "hwm" |
| people.age = 18 |
| |
| console.log(people) |
复制
3.2 对象作为参数传递
方法一:
| private ParamObj(objT: {name: string, age: number}) { |
| let people = objT |
| console.log(objT) |
| } |
| |
| let people = {name: "hwm", age: 18} |
| this.ParamObj(people) |
复制
方法二:
| interface obj { |
| [idx: string]: any |
| } |
| |
| private ParamObj(objT: obj) { |
| let people = objT |
| console.log(objT) |
| } |
| |
| let people:obj = {} |
| people.name = "lll" |
| people.age = 20 |
| this.ParamObj(people) |
复制
3.3 方法返回对象
| private ReturnObj(): {name: string, age: number}{ |
| let people = {name: "hwm", age: 18} |
| return people |
| } |
| |
| let res = this.ReturnObj() |
| console.log(res) |
复制
3.4 对象数组
| let tbl: {name: string, age: number}[] = [] |
复制