I'm new to TypeScript, and trying out custom type declaration through this simple snippet.
The script
I have this script:
// app.ts
type Customer = {
name: String,
isFrequentVisitor: Boolean,
}
type Order = {
buyer: Customer,
itemName: String,
itemPrice: number,
isConfirm: Boolean
}
function placeOrder (user: Customer): Order {
let order: Order
order.buyer = user
order.itemName = 'Raspberry Pi'
order.itemPrice = 1000
order.isConfirm = true
return order
}
let person: Customer = {
name: 'John',
isFrequentVisitor: false
}
let newOrder: Order = placeOrder(person)
if (newOrder.isConfirm) {
console.log('The order has been confirmed. Check details below:')
console.log(newOrder)
} else {
console.log('The order has not been confirmed yet.')
}
The problem
I'm able to run $ tsc app.ts successfully (without any errors on the console), and see app.js next to the file.
However, running $ node app.js, I get the following error -
/tmp/app.js:3
order.buyer = user;
^
TypeError: Cannot set property 'buyer' of undefined
Also, if it may be useful, I have linked the compiled app.js here.
I have worked with custom types in Golang, and they work just fine in a similar context.
I'm not sure what am I missing here.
Also, isn't it the reason behind using TypeScript, so that we can catch errors before they occur at runtime.
I'd appreciate a beginner-friendly answer. Thank you.
Specifications
- using TypeScript Version 3.8.3
- using Node version 14.4.0