I know type guards can be used to distinguish between unioned types. But is it possible to detect property existence on an unknown type being passed in?
This code does not work.
function foo(bar: unknown | { createdDate: Date }) {
if (bar.createdDate)
alert(bar.createdDate); //Doesn't work
}
Neither does this:
function foo(bar: unknown | { createdDate: Date }) {
if ('createdDate' in bar)
alert(bar.createdDate); //Doesn't work
}
Note: Changing the type of bar to any does work, but the compiler is not narrowing the type inside the if statement. It is typing bar.createdDate as any.
I've also tried generic versions of this function to avail.
function foo<T extends (unknown | { createdDate: Date })>(bar: T) {
if ('createdDate' in bar)
alert(bar.createdDate); //Doesn't work
}
Is there a way to confirm existence of a property on an unknown type and then have the compiler narrow the type appropriately?