I am facing a similar situation,
type Field1Type = {
a: string;
}
type Field2Type = {
b: string;
c: number;
}
type ObjType = {
field: Field1Type | Field2Type
}
const field = {
b: ""
c: 0
}
const obj = { field } as ObjType
if (some_condition) {
// TypeScript gives an error: Property 'b' does not exist on type 'Field1Type'.ts(2339)
console.log(obj.field.b)
}
My scenario involves having an object with a field that can have different types.
When trying to access the field properties, I receive the TypeScript warning because it cannot determine if the field is of type Field1Type
or Field2Type
.
This issue can be addressed by:
if (some_condition) {
const temp = obj.field as Field2Type
// TypeScript errors: Property 'b' does not exist on type 'Field1Type'.ts(2339)
console.log(temp.b)
}
However, this solution may not seem very elegant.
My question is, is there a more graceful way to assert the field within the condition?