Skip to content

Instantly share code, notes, and snippets.

@nikgraf
Created February 25, 2016 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikgraf/99052c9747a646561596 to your computer and use it in GitHub Desktop.
Save nikgraf/99052c9747a646561596 to your computer and use it in GitHub Desktop.
someOtherVariable doesn't trigger an error!?
type UnicornEditorState = {
editorState: any,
}
export default class UnicornEditor extends Component {
state: UnicornEditorState = {
editorState: EditorState.createEmpty(compositeDecorator),
someOtherVariable: 'Should throw an error?',
};
render() {
return (
<div>
Hello World
</div>
);
}
}
@jeffmo
Copy link

jeffmo commented Feb 25, 2016

No (should not throw an error), but I believe it means you won't be able to access this.state.someOtherVariable anywhere in the body.

{editorState: EditorState, someOtherVariable: string} is a valid subtype of {editorState: EditorState} (the latter is most restrictive/general).
But once you type this.state as the more restrictive/general type, you have to treat it that way forever

@nikgraf
Copy link
Author

nikgraf commented Feb 25, 2016

yes indeed, accessing this.state.someOtherVariable triggers an error as well as trying to set it in setState.

Do I understand correctly that when defining types it's not strict and all kinds of subtypes are still valid in Flow in general? Just React does a strict validation when accessing due Shape here?

@jeffmo
Copy link

jeffmo commented Feb 25, 2016

Do I understand correctly that when defining types it's not strict and all kinds of subtypes are still valid in Flow in general?

Mostly right, yea. It boils down to variance:

class Foo {
  someProp: {bar: string};
}
let foo = new Foo();

// This assignment is safe
foo.someProp = {
  bar: "string stuff",
  baz: 42,
  blah: new Date(),
};


// This assignment is safe
foo.someProp = {
  bar: "string stuff",
};

// This is safe
let str: string = foo.someProp.bar;

// This is not safe because the `someProp` property type includes *all* objects 
// with a "bar":string property (but not all objects with a "bar":string property
// have a "baz":number property)
let num: number = foo.someProp.baz;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment