Having some difficulty determining if the property value of an object is undefined when accessed dynamically with bracket notation. Here's a snippet of my code:
function toBritishDate(date: Date | string): string {
console.log(date)
return "foo"
}
function myFunc() {
const project: { start_date?: string; end_date?: string } = {
start_date: '2023-09-13',
end_date: '2023-09-29',
};
const array: ("start_date" | "end_date")[] = ['start_date', 'end_date']
array.forEach((element) => {
if (project[element] !== undefined) {
console.log(toBritishDate(project[element]))
}
});
}
Feel free to check out the playground link.
Error encountered when calling toBritishDate on match.project[element]:
Argument of type 'string | undefined' is not assignable to parameter of type 'string | Date'. Type 'undefined' is not assignable to type 'string | Date'. (tsserver 2345)
It appears that
match.project[element] !== undefined
solely confirms if the property exists, without checking if the actual value is undefined. Any suggestions on how to confirm both the existence of the property and ensure it has a defined value?