flow icon indicating copy to clipboard operation
flow copied to clipboard

Options object destroys type checking.

Open AndrewSouthpaw opened this issue 8 years ago • 2 comments

A simple options object applied as a spread do an object seems to mess up type checking.

type Foo = { a: number, b: 'foo' }

const newFoo = (a: number, options?: {} = {}): Foo => ({
  a,
  b: 'foo',
  ...options
})

newFoo(1, { b: 'a' }) // No error!

Here's a Flow Try link.

I would expect it to throw an error. Am I doing something wrong?

AndrewSouthpaw avatar Dec 07 '17 23:12 AndrewSouthpaw

I'm not sure why this doesn't trigger an error, but if you change the type of your options to $Shape<Foo> it will at least check that options has valid properties:

type Foo = { a: number, b: 'foo' }

const newFoo = (a: number, options?: $Shape<Foo> = {}): Foo => ({
  a,
  b: 'foo',
  ...options
})

// Error: Expected string literal `foo`, got `a` instead
newFoo(1, { b: 'a' });

kevanstannard avatar Dec 08 '17 20:12 kevanstannard

Argh! I forgot about $Shape! Rats, that's exactly the utility method I was trying to figure out. Thanks @kevanstannard.

AndrewSouthpaw avatar Dec 09 '17 01:12 AndrewSouthpaw