Can an optional and required field of merged interfaces yield a required field?
I have this case from using the mongoose library, in which my domain object, A, might have a DB _id, but the mongoose.Document always has an _id. I use type A when not in the mongoose portions of the app, and type ADocument only within those parts that deal directly with mongoose. Note that mongoose defines Document to contain _id like this:
interface Document {
_id: string;
}
I tried to model the A - ADocument relationship like this:
interface A {
_id?: string;
}
interface ADoc extends A, mongoose.Document {
}
but I get this error: _Interface 'ADoc' cannot simultaneously extend types 'A' and 'Document': Named properties 'id' of types 'A' and 'Document' are not identical.
I can get around this error by making _id be either optional in both definitions, or required in both.
I expect that the compiler can infer that _id is now required in ADoc. Is the current behavior of issuing an error the correct behavior? If so, does it make sense to merge such fields so they become required?
Hm, I'm not sure about the actual semantics as per the spec behind this (a little hard for me to access it), but if you explicitly declare _id in ADoc, you should be able to get rid of this error.
interface Document {
_id: string;
}
interface A {
_id?: string;
}
interface ADoc extends A, Document {
_id: string;
}
I followed your advice, and placed _id in the merged classes explicitly, and this removed the errors. Thanks.
As for the spec , I couldn't find anything in the spec that addresses this case. And regarding the semantics, it seems to me that optional may be satisfied by required, if optional is interpreted as "might be present", and required is interpreted as "is present". Which is what your suggested fix does as well.
The spec addresses this in section 7.1:
The following constraints must be satisfied by an interface declaration or otherwise a compile-time error occurs:
- [...]
- Inherited properties with the same name must be identical (section 3.8.2).
The relevant definition of "identical member" at 3.8.2 is:
Two members are considered identical when
- they are public properties with identical names, optionality, and types,
In general we only ever merge properties when they are completely identical.
@RyanCavanaugh so how does having merging field in target interface fix the error? Does it only check convertibility to interfaces extended from?
@Igorbek You've now overridden the declarations from the inherited members. The compiler then checks that with the overridden declaration ADoc is a subtype of A and a subtype of Document.
looks like no further information required. closing.
Thanks @DanielRosenwasser