如何 ‘初始化’ 一个 TypeScript 对象?

huangapple go评论67阅读模式
英文:

How to 'initialize' a TypeScript object?

问题

It appears that when fetching JSON data from a MongoDB database and casting it to a TypeScript class like Team, the constructor for Team is not being triggered. This behavior is likely due to how MongoDB's driver for JavaScript/TypeScript works.

MongoDB drivers often create instances of classes based on the data retrieved from the database without calling the class constructor directly. Instead, they typically create objects with the data fields populated but don't invoke the constructor method.

So, in your case, when you fetch a Team from MongoDB, it's likely being constructed without invoking the constructor you defined. This is a common behavior in many ORMs and database libraries to ensure that objects match the data stored in the database.

If you need to perform initialization logic when a Team is fetched from the database, you may want to create a separate method within the Team class to handle that initialization, and then call that method explicitly after fetching the data from MongoDB. This way, you can ensure that your desired setup logic is executed when needed.

英文:

Seems, fetching a json from a mongodb datbase, and cast it will not trigger typescript constructor, why? What is wrong?

I have a Team class

export class Team {
	transformations: { [transformationId: string]: Transformation }
	typeTrees: { [ttMakerId: string]: TTMaker }

	constructor() {
		console.log('NewTree constructor called')
		this.transformations = {}
		this.typeTrees = {}
	}
}

I am downloading a json, which would conform as type to Team:

export default async function handler(
	req: NextApiRequest,
	res: NextApiResponse<string | null>
) {
	const transformationId = req.query.transformationId as string
	const text = req.query.text as string
	try {
		const { mongoClient } = await connectToDatabase()
		const db: Db = mongoClient.db('datamapper')
		const collection = db.collection<Team>('team')
		const team: Team | null = await collection.findOne({
			name: 'responsive',
		})

But when I add a breakpoint to constructor Team, it will not be hit, why?

如何 ‘初始化’ 一个 TypeScript 对象?

答案1

得分: 1

这将使用新关键字创建Team类的新实例,然后使用Object.assign()将获取的数据分配给它。这应该会触发构造函数。

英文:
const teamData = await collection.findOne({ name: 'responsive' });
const team = Object.assign(new Team(), teamData);

This will create a new instance of the Team class using the new keyword, and then assign the fetched data to it using Object.assign(). This should trigger the constructor.

答案2

得分: -1

为了初始化一个Team类的对象,你需要使用new运算符,如下所示:

const Team: Team = new Team();

通过使用new运算符,它将触发Team类的构造函数。

希望能帮助到你!

英文:

To initialize an object of Team class, you need to use the new operator like so:

const Team: Team = new Team();

by using the new operator it will trigger the constructor of the Team class.

Hope it helps!

huangapple
  • 本文由 发表于 2023年5月25日 06:34:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定