As I embark on my journey with TypeScript, please bear with me if this is not the conventional way of doing things.
I have a few objectives in transitioning this JavaScript code to TypeScript.
Item = {}
Item.buy = function (id) {}
Item.sell = function (id) {}
I am striving to enable intellisense for autocompleting Item.
with either buy or sell. Additionally, I aim to use dot notation to define these methods in separate files without consolidating everything within the initial bracket. So, my approach looks something like this:
interface Item {}
const Item: Item = {};
interface Item {
buy?: Function
}
Item.buy = function () {
Item.render()
return "bought"
}
interface Item {
sell?: Function
}
Item.sell = function () {
Item.render()
return "sold"
}
interface Item {
render?: Function
}
Item.render = function () {
return 1
}
The current issue lies in render being an optional property, resulting in the error message:
Cannot invoke an object which is possibly 'undefined'.
How can I instruct TypeScript not to flag this as an error? Since Item is not a class and will always have the render method, the error check is unnecessary. In other words, it's not truly optional; I only made it so to address the const Item: Item = {};
error that arises when it's not optional.
Is there a way to communicate this to TypeScript or adopt a different pattern from the outset?