Flow: Allow inferring type when using Object.assign

Created on 3 Dec 2015  路  2Comments  路  Source: facebook/flow

I would like to do something like this:

class Foo {
  str: string;
  num: number;

  constructor(input: Object) {
    Object.assign(this, input);
  }
}

// Typecheck failure is desired...
console.log(new Foo({ str: 1, num: 'foo' }));

Which results in no errors....

The other variant (which I think makes more sense)

class Foo {
  str: string;
  num: number;

  constructor(input: $Shape<Foo>) {
    Object.assign(this, input);
  }
}

// Typecheck failure is desired...
console.log(new Foo({ str: 1, num: 'foo' }));

Will correctly check the type but also report errors about Object.assign:

src/api/metrics.js:30
 30:     Object.assign(this, input);
         ^^^^^^^^^^^^^^^^^^^^^^^^^^ Object.assign
 30:     Object.assign(this, input);
         ^^^^^^^^^^^^^^^^^^^^^^^^^^ Object.assign. Property not found in
 25: class Foo {
           ^^^ Foo

src/api/metrics.js:35
 35: console.log(new Foo({ str: 1, num: 'foo' }));
                         ^^^^^^^^^^^^^^^^^^^^^^ property `str` of object literal
 35: console.log(new Foo({ str: 1, num: 'foo' }));
                                ^ number. This type is incompatible with
 26:   str: string;
            ^^^^^^ string

src/api/metrics.js:35
 35: console.log(new Foo({ str: 1, num: 'foo' }));
                         ^^^^^^^^^^^^^^^^^^^^^^ property `num` of object literal
 35: console.log(new Foo({ str: 1, num: 'foo' }));
                                        ^^^^^ string. This type is incompatible with
 27:   num: number;
            ^^^^^^ number


Found 3 errors

If I type my values twice (once in the class) and again as a type alias for the constructor this works as expected (but I have to type these values twice :/)

It would be nice if this could be inferred somehow :)

Most helpful comment

You can now use type spreads for this effect 馃帀

class Foo {
  str: string;
  num: number;

  constructor(input: {...Foo}) {
    Object.assign(this, input);
  }
}

// Typecheck failure is desired...
console.log(new Foo({ str: 1, num: 'foo' }));

https://flow.org/try/#0MYGwhgzhAEBiD29oG8BQ1oQC4CcBcmuAlgHYDmA3OtCQK4C2Bd9ARgKY5XXDwnY61gWeDgAUpAA60sBZADoFCeAF8AlCmoYA8iwBWbIXMgQiZEqKwALIhAA00SdNVUMy1G9QB6T9AAqATwkDSwMAa2gAMzAiEFocNgcYABM2E3ikhTlUHj54EDY5EHgyURI2AHc4RFFkQnxoAEZ7ZgIAcgjEVug1Z1QgA

All 2 comments

These seem to be the same errors as in #1596, right?

You can now use type spreads for this effect 馃帀

class Foo {
  str: string;
  num: number;

  constructor(input: {...Foo}) {
    Object.assign(this, input);
  }
}

// Typecheck failure is desired...
console.log(new Foo({ str: 1, num: 'foo' }));

https://flow.org/try/#0MYGwhgzhAEBiD29oG8BQ1oQC4CcBcmuAlgHYDmA3OtCQK4C2Bd9ARgKY5XXDwnY61gWeDgAUpAA60sBZADoFCeAF8AlCmoYA8iwBWbIXMgQiZEqKwALIhAA00SdNVUMy1G9QB6T9AAqATwkDSwMAa2gAMzAiEFocNgcYABM2E3ikhTlUHj54EDY5EHgyURI2AHc4RFFkQnxoAEZ7ZgIAcgjEVug1Z1QgA

Was this page helpful?
0 / 5 - 0 ratings