flow icon indicating copy to clipboard operation
flow copied to clipboard

Spreading a generic value allows adding unexpected properties to it

Open noppa opened this issue 4 years ago • 1 comments

Flow version: 0.159.0

Expected behavior

type A = {|foo: string, bar: string|}

function addBar<T>(val: T): T {
    return {...val, bar: 1}
}

const a: A = {foo: '', bar: ''}
const a2: A = addBar(a)

a2.bar.toUpperCase() // boom

I'd expect Flow to error at return {...val, bar: 1}, since nothing in <T> says that the object can have property bar.
Flow correctly errors if I try to directly assign to the object with val.bar = 1

Actual behavior

Flow doesn't show any errors, the code only fails at runtime. Flow allows both overwriting existing properties with incorrect types and adding completely new arbitrary properties to it (even though the type is exact).

  • Link to Try-Flow or Github repo: Try-Flow

noppa avatar Sep 14 '21 12:09 noppa

Thanks for the report! We've had some improvements to the soundness of the interaction of generics and spreads to the to-do list for a while, it looks like this hits on one of the ways that they interact in an unsound way.

mvitousek avatar Sep 20 '21 18:09 mvitousek