While running tsc
locally on an example file named example.ts
, I encountered some unexpected behavior. In particular, when I created the object onePropMissing
and omitted the property c
which is not optional according to the interface definition, I did not receive any errors.
Subsequently, I added another example called oneExtraProp
where an additional property was included, anticipating a failure due to the extra property.
To my surprise, TSC flagged an error for extraAndOneMissing
even though I expected it to pass based on the previous examples.
interface InterfaceEverythingRequired {
a: string;
b: string;
c: number;
}
// This should be fine, and indeed it is
const allPropsPresent = { a: 'a', b: 'b', c: 1 } as InterfaceEverythingRequired;
// Expected warning for missing prop 'c', but no error occurs
const onePropMissing = { a: 'a', b: 'b' } as InterfaceEverythingRequired;
// Expected warning for extra prop, but TSC does not flag it
const oneExtraProp = { a: 'a', b: 'b', c: 3, extraProp: 'no-issues' } as InterfaceEverythingRequired;
// Despite no warnings in the previous two cases, TSC raises an error here
const extraAndOneMissing = { a: 'a', b: 'b', extraProp: 'what?' } as InterfaceEverythingRequired;
I am puzzled by this behavior. Why are errors being inconsistently detected?
The specific error message received reads:
Type '{ a: string; b: string; extraProp: string; }' cannot be
converted to type 'InterfaceEverythingRequired'.
Property 'c' is missing in type '{ a: string; b: string;
extraProp: string; }'.