Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: strange behavior on validating function return object type [duplicate]

I discovered that my return type are not validated as expected by typescript when I use the const myFn: () => MyObjType notation. Here is a relevant ts playground and the code:

type MyObj = {
    a?: string
    b?: number
}

const fn = function (): MyObj {
    return {
        a: 'string',
        shouldErr: 'err', // has error
    }
}

function fn2(): MyObj {
    return {
        a: 'string',
        shouldErr: 'err', // has error
    }
}

const fn3: () => MyObj = () => ({
    a: 'string',
    shouldErr: 'err', // has NO ERROR
})

const fn4: () => MyObj = function ()  {
    return {
        a: 'string',
        shouldErr: 'err',  // has NO ERROR
    }
}

In my code, the typings can be simplified as:

type MyComplexObj = {
  myFn(): ReturnType
}

So I am not sure on my options to obtain the behavior I expect.

Could you explain why return types are validated like this? Is there a way to get around this and "strictly" validate return type so that, in the previous example, the shouldErr prop is in error ?

like image 570
TOPKAT Avatar asked Jun 02 '26 05:06

TOPKAT


1 Answers

The type

type MyObj = {
    a?: string
    b?: number
}

includes

return {
    a: 'string',
    shouldErr: 'err',  // has NO ERROR
}

When you specify the exact return type of a function, you get an error. The same would happen if you specified it in the 2 examples below:

const fn3: () => MyObj = (): MyObj => ({
    a: 'string',
    shouldErr: 'err', // will show an error now
})
like image 103
Vladyslav Zavalykhatko Avatar answered Jun 05 '26 01:06

Vladyslav Zavalykhatko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!