In the example below, there are two places I can't wrap my head around, marked with (1) and (3)
Near (1), we're assigning a function which only knows how to handle string
to a property which should know how to handle string | undefined
. There's no TS error, and the succeeding call would result in a Runtime Error
Near (2), TS is able to correctly give an error, when arrow function is passed via reference, but near (3) when an arrow function is passed to be assigned to method which should handle string | undefined
, everything is once again OK to Typescript (although it shouldn't)
I would really love to know why TS is behaving this way, since my example suggests that method and arrow function in interfaces are not really the same.
Here's a TS Playground to play with
P.S. I browsed through a few SO questions, including this one about arrow function vs. normal function inside interface but none of them gave the answer to my problem.
const arrowAcceptingString = (str: string) => "some string";
function functionAcceptingString(str: string) { return str[0] ?? "some string"; }
interface MethodCanHandleStringOrUndefined{
handleText(text: string | undefined): string;
}
interface ArrowCanHandleStringOrUndefined {
handleText: (text: string | undefined) => string;
}
// (1) should be TS error -- `functionAcceptingString` can't handle `string | undefined`
const testMethod: MethodCanHandleStringOrUndefined = {
handleText: functionAcceptingString
}
// (2) Correct TS error ✅
const testArrowFunction: ArrowCanHandleStringOrUndefined = {
handleText: arrowAcceptingString,
}
// (3) should be TS error -- `arrowAcceptingString` can't handle `string | undefined`
const testArrowToMethod : MethodCanHandleStringOrUndefined = {
handleText: arrowAcceptingString
}
testMethod.handleText(undefined); // failing in runtime
testArrowToMethod.handleText(undefined); // failing in runtime