4

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?

3
  • What's the question? If you think this is wrong I'd raise an issue on the GitHub page for typescript. why the following doesnt throw an error because the typescript transpiler doesn't ¯\_(ツ)_/¯ Commented Feb 11, 2021 at 11:13
  • Why does the callback function in format requires to be explicitly set a return type to show the error and why the first case is not showing the error? OP feels like typing Test twice should not be required (the later case) when format function clearly indicates what the return type is. Commented Feb 11, 2021 at 11:16
  • @Liam hey - yeah Ive clarified my question with - is this a expected typescript limitiation. Commented Feb 11, 2021 at 11:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that. Does that mean as long as it extends Test it will pass? And therefore I require explicitly setting the return type then?
Object literals undergo excess property checking only when there's explicit target type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.