After some investigation, I came to the realization that TypeScript does not validate my return types as anticipated when using the const myFn: () => MyObjType
syntax. I ran some tests on the TypeScript playground and examined the code:
type MyObj = {
a?: string
b?: number
}
const fn = function (): MyObj {
return {
a: 'string',
shouldErr: 'err', // should throw an error
}
}
function fn2(): MyObj {
return {
a: 'string',
shouldErr: 'err', // should throw an error
}
}
const fn3: () => MyObj = () => ({
a: 'string',
shouldErr: 'err', // no error raised
})
const fn4: () => MyObj = function () {
return {
a: 'string',
shouldErr: 'err', // no error raised
}
}
In a more simplified manner, the typings in my code look like this:
type MyComplexObj = {
myFn(): ReturnType
}
Now I am uncertain about the options available to achieve the desired behavior.
What is causing return types to be validated in this way? Is there a workaround to ensure strict validation of return types, so that, in the example given, the shouldErr
property triggers an error?