文章详情页
TypeScript为对象动态添加属性代码示例
浏览:4日期:2022-06-13 10:36:24
目录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// value1object_name.key4// ['content1', 'content2']2.TypeScript 类型模板var sites = { site1: '', site2: 0, sayHello: function () { } // 类型模板};sites.site1 = 'site1'sites.site2 = 2sites.sayHello = function () { console.log('hello ' + sites.site1 + sites.site2);};sites.sayHello();// hello site1 23.为对象动态添加属性如果我们使用以上的方法定义对象是无法做到为对象动态添加属性
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 = 18console.log(people)// { name: 'hwm', age: 18 }3.2 对象作为参数传递方法一:
private ParamObj(objT: {name: string, age: number}) { let people = objT console.log(objT)}let people = {name: 'hwm', age: 18}this.ParamObj(people)// {name: 'hwm', age: 18}方法二:
interface obj { [idx: string]: any}private ParamObj(objT: obj) { let people = objT console.log(objT)}let people:obj = {}people.name = 'lll'people.age = 20this.ParamObj(people)// {name: 'lll', age: 20}3.3 方法返回对象private ReturnObj(): {name: string, age: number}{ let people = {name: 'hwm', age: 18} return people}let res = this.ReturnObj()console.log(res)// {name: 'hwm', age: 18}3.4 对象数组let tbl: {<!--{C}%3C!%2D%2D%20%2D%2D%3E-->name: string, age: number}[] = []总结到此这篇关于TypeScript为对象动态添加属性的文章就介绍到这了,更多相关TS对象动态添加属性内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
标签:
JavaScript
排行榜