_id
is marked as optional, TS warns about this and it is right. The code logic is probably flawed and you attempt to fool TS instead of fixing the logic.
If _id
must be optional then either doSomethingWithId()
should allow undefined
as argument or track()
must call doSomethingWithId()
only if it is sure that _id
is set.
On the other hand, _id
is an identifier and an identifier is never undefined
. It represents the identity of the object; it cannot be undefined
and it must be set when the object is created.
Your class does not have a constructor and this makes its instances just regular objects with a fancy prototype. The purpose of a class is to enforce the creation and usage of entities that are always consistent. The code const x = new Blog()
produces an empty object. It's _id
property is undefined
(_id
is not even present in x
).
This is how it can be implemented using OOP at its full potential and not just as a buzzword:
class Blog {
public constructor(private id: number) { }
async track() {
doSomethingWithId(this.id)
}
}
And this is how it is used:
const id = await getIdOfBlog()
const x = new Blog(id)
Now x
is a valid object. It has a value in its identity property.
This approach has other advantages too. I guess getIdOfBlog()
gets the value from a database or another external resources. In the tests of class Blog
you don't want to wait for the code that accesses external resources; you don't even want to run such code in tests.
In the tests of class Blog
you can simply create an instance of the class as new Blog(42)
then use it.