Last active
April 8, 2019 19:13
-
-
Save matt-erhart/d8929124b03e62fc794b12a31ee7fbe9 to your computer and use it in GitHub Desktop.
define types from defaults and return values for typescript react redux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const SomeComponentDefaults = { | |
| props: { | |
| exampleProp: '' // start with '' and only allow strings. ts will prevent e.g. numbers being passed in as props | |
| }, | |
| state: { | |
| exampleObjArray: [] as { source: ""; target: ""; id: "" }[], // use 'as' when your default is empty/undefined so ts knows what will be there | |
| exampleNoDefault: undefined as number | string, // ideally we should have something as a default because undefined can cause errors | |
| exampleNumber: 0 //is a number now, will be a number always. don't need 'as', | |
| exampleUser: {name: '', email: '', age: 0} // each type will stay the same so don't need 'as' | |
| } | |
| }; | |
| export class GraphContainer extends React.Component< | |
| typeof GraphContainerDefaults.props, //'typeof' will infer types from any object | |
| typeof GraphContainerDefaults.state | |
| > { | |
| static defaultProps = GraphContainerDefaults.props; // 'static defaultProps' is a react specific thing | |
| state = GraphContainerDefaults.state; // 'state =' at this level in the class initializes the react state, 'state' is special in a react class. | |
| render () { | |
| return (<div> | |
| now you can change one default object and the types will propagate into the commonent at this.props and this.state will have autocompete. | |
| </div>) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment