Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type?
There are many questions on StackOverflow about this issue, but none of them explain why it happens, why it's supposed to be like this, or how to fix the error with the expected outcome.
Since 2017, there has been an open Github issue thread on the same topic - TS Proposal : "Interface incorrectly extends interface" - sub-interface method overload OR override ?
Where is my understanding of extended interfaces incorrect?
Please assist a newcomer TS developer!!! Thanks...
// ------------------------ Types Declaration ----------------
interface ServerRequest {
url: string,
method: string,
body: string | undefined
}
interface ExtendedServerRequest extends ServerRequest {
orignal_url: string | undefined
}
type FunctionOrignal = (req: ServerRequest)=> void
type FunctionOverridden = (req: ExtendedServerRequest)=> void
interface ShortHandOptions {
onSend: FunctionOrignal
}
interface ExtendedShortHandOptions extends ShortHandOptions {
onSend: FunctionOverridden
}
// ------------------------ Test ----------------------------
console.log('------------------------------------------------');
function test(opts: ShortHandOptions) {
opts.onSend({
url: 'https://httpbin.org/get',
method: 'GET'
} as ServerRequest);
}
var func1: FunctionOrignal = (req) => {
console.log('FunctionOrignal', req.url);
},
func2: FunctionOverridden = (req) => {
console.log('FunctionOverridden', req.orignal_url);
};
test({ onSend: func1 } as ShortHandOptions);
test({ onSend: func2 } as ExtendedShortHandOptions);
This results in:-
Interface 'ExtendedShortHandOptions' incorrectly extends interface 'ShortHandOptions'.
Types of property 'onSend' are incompatible.
Type 'FunctionOverridden' is not assignable to type 'FunctionOrignal'.
Types of parameters 'req' and 'req' are incompatible.
Property 'orignal_url' is missing in type 'ServerRequest' but required in type 'ExtendedServerRequest'.
This should work as long as test
function calls onSend
with an argument of type ShortHandOptions
, i.e. an argument with at least the following properties { url, method, body }.