Typescript 对象解析

52 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第13天,点击查看活动详情

TypeScript中的对象允许我们使用我们选择的组合定义自定义数据类型。 我们可以通过两种方式在TypeScript中创建对象。 一个是使用新的Object()构造函数,另一个是使用花括号 - {}。 下面的示例演示了如何使用这两种技术创建相同的对象。

let planet = new Object();
let planet = {};

对象可以在其中定义属性。 在下面给出的示例中,我们创建了一个具有四个属性的Object Planet,name,galaxy,numberOfMoons和weight。 要定义对象的蓝色打印,我们可以在TypeScript中使用接口。 一旦定义了接口,我们就可以创建该接口的对象。 在下面的示例中,我们创建了Planet接口,然后我们填充了一个Planet对象,其属性代表Planet Earth。 然后我们访问了Planet Earth的属性并将它们打印到日志中。

interface Planet{
	name: string;
	galaxy: string;
	numberOfMoons: number;
	weight: number;
}

//Object with properties
let planet: Planet = {
    name : "Earth",
    galaxy : "Milky Way",
    numberOfMoons : 1,
    weight : 100000
};

console.log("Planet Name :- " + planet.name);
console.log("Planet Galaxy :- " + planet.galaxy);
console.log("Planet Number of Moons :- " + planet.numberOfMoons);
console.log("Planet Weight :- " + planet.weight);

运行结果:

Planet Name :- Earth
Planet Galaxy :- Milky Way
Planet Number of Moons :- 1
Planet Weight :- 100000

您可以直接在对象上更改属性。 我们可以用点(。)运算符引用属性名称。 在下面的例子中,我们将星球的星系属性改为仙女座星系。 我们还可以通过将属性作为方括号[]内的字符串传递来访问属性。

interface Planet{
	name: string;
	galaxy: string;
	numberOfMoons: number;
	weight: number;
}

//Object with properties
let planet: Planet = {
    name : "Earth",
    galaxy : "Milky Way",
    numberOfMoons : 1,
    weight : 100000
};

planet.galaxy = "Andromeda";
console.log("Planet Galaxy after change :- " + planet.galaxy);

// You can also access Property names using square brackets and passing String.
console.log("Planet Galaxy :- " + planet["galaxy"]);

运行结果:

Planet Galaxy after change :- Andromeda
Planet Galaxy :- Andromeda

我们可以使用for .. in循环迭代Object的属性。 在下面的示例中,我们使用.. in循环迭代Planet Earth的属性,然后访问属性值。

interface Planet{
	name: string;
	galaxy: string;
	numberOfMoons: number;
	weight: number;
}

// Iterating properties.
let planet: Planet = {
	name : "Earth",
	galaxy: "Milky Way",
	numberOfMoons : 1,
	weight : 100000
};

for(let prop in planet)
{
	console.log("Planet " + prop + " :- " + planet[prop]);
}

运行结果:

Planet name :- Earth
Planet galaxy :- Milky Way
Planet numberOfMoons :- 1
Planet weight :- 100000