Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript generic callback object strictness

Im struggling to understand why the following doesnt throw an error

type Callback<T> = () => T

function format<V>(callback: Callback<V>): V {
    return callback()
}

type Test = {foo: string}

format<Test>(() => {
    return {
        foo: 'hello',
        bar: 'dd' // I expect an error to be here as `bar` does not exist on type Test
    }
})

// if I explicitly set the return type in the callback then I get the correct error

format<Test>((): Test => {
    return {
        foo: 'hello',
        bar: 'dd' // this now errors as I have set the return type.
    }
})

I cant help but feel this is a duplication?

Is this a typescript limitation and is "as expected", or are my types incorrect?

like image 212
amwill04 Avatar asked Feb 17 '26 16:02

amwill04


1 Answers

Excess property checking is not triggered because callback doesn't have explicit type notation. Typescript infers its type as () => { foo: string; bar: string } which is assignable to Callback<Test>.

Have a look at this example:

type Callback<T> = () => T

type Test = { foo: string }

const extendedCallback = () => ({ foo: 'hello', bar: 'bar' }) // inferred as () => { foo: string; bar: string }

const callback: Callback<Test> = extendedCallback // assignment is valid

Playground

like image 175
Aleksey L. Avatar answered Feb 20 '26 10:02

Aleksey L.