1

I'm guessing I'm not doing something quite right, but I'm not sure what it is.

I'm wanting to write a type that describes a function and it's return type.

type SomeFn<Output extends Record<string, any>> = ( x: Record<string, any> ) => Output

But when I use it, I don't get errors when I would expect them.

type ExpectedOutput = { num1: number }

const testFn1: SomeFn<ExpectedOutput> = x => ( { foo: 'foo', num1: 1 } )
//                     should error, but doesn't ^^^^^^^^^^ 

const testFn2: SomeFn<ExpectedOutput> = x => {
    const data = { foo: 'foo', num1: 1 }
    return data
    //     ^^^^ should error, but doesn't
}

What am I doing wrong?

1

1 Answer 1

1

That's because of Typescript's structural typing :

Something like this is valid in TS :

type SomeFn = () => { num1: 1 }    
const testFn1: SomeFn = () => ({ num1: 1, foo: 'bar' })

What you might want is Exact types but it's an open ticket at the moment.

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

Comments

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.