TypeScript为对象动态添加属性代码示例

来自:网络
时间:2023-07-25
阅读:
目录

1.定义

TypeScript 对象是包含一组键值对的实例。 值可以是标量、函数、数组、对象等,如下实例:

var object_name = { 
    key1: "value1", // 标量
    key2: "value",  
    key3: function() {
        // 函数
    }, 
    key4:["content1", "content2"] //集合
}

//访问对象
object_name.key1	// value1
object_name.key4	// ["content1", "content2"]

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();	// hello site1 2

3.为对象动态添加属性

如果我们使用以上的方法定义对象是无法做到为对象动态添加属性

let people = {
    name: "hwm",
    age: 18,
    sayHello: ()=> {}
}

people.sex = "man"

以上代码会报错:

TypeScript为对象动态添加属性代码示例

3.1 解决方法

定义一个包含数组属性的接口,让对象实现该接口

interface obj {
    [idx: string]: any
}
let people: obj = {}
people.name = "hwm"
people.age = 18
console.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 = 20
this.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}[] = []

总结

返回顶部
顶部