I encountered an issue with my code:
interface Wide {
prop: string | undefined
}
interface Narrow {
prop: string
}
class Foo {
prop: string
constructor({ prop }: Narrow) {
this.prop = prop
}
}
const array = [{ prop: undefined }, { prop: 'foo' }]
array.forEach((obj: Wide) => {
if (obj.prop && typeof obj.prop === 'string' && obj.prop !== undefined) {
console.log(new Foo({ ...obj }))
// Type 'undefined' is not assignable to type 'string'.
}
})
In normal circumstances, I would expect Typescript to infer that when the if
condition is met, it implies that the current obj
being iterated over has a defined property prop
with the type string
. However, I am unable to make it work as expected.