Guest User

Untitled

a guest
Oct 16th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. # Coding guidelines
  2.  
  3. ## `null` and `undefined`
  4.  
  5. Use `undefined` wherever is possible. Do not use null.
  6.  
  7. ## Umbrella modules
  8.  
  9. Do not use umbrella modules (index.ts) for state and features. This prevents issues with cyclic imports.
  10.  
  11. ## Use invariants
  12.  
  13. When some optional values depend on a value, use invariants to make sure that contracts are not violated:
  14.  
  15. ```typescript
  16. export interface IProps {
  17. isEditable?: boolean;
  18. onValueChange?: () => any;
  19. }
  20.  
  21. export default class Editor extends Component<IProps> {
  22. public render() {
  23. const { isEditable, onValueChange } = this.props;
  24.  
  25. if (isEditable) {
  26. invariant(
  27. onValueChange,
  28. "Editor is editable, but onValueChange is missing",
  29. );
  30. }
  31.  
  32. // Some other code
  33. }
  34. }
  35. ```
  36.  
  37. With invariants, we can follow a safer way to access e.g. GraphQL data which might be undefined until the data is loaded. To prevent errors caused by undefined values, define a method to get the data and use it everywhere you need to access the data, like so:
  38.  
  39. ```typescript
  40. public render() {
  41. const { title, body } = this.getPost();
  42. // skipped
  43. }
  44.  
  45. // skipped
  46.  
  47. private getPost = () => {
  48. const { postData, slug } = this.props;
  49.  
  50. // Use invariant to throw an error when the required value is undefined
  51. invariant(postData.post, `No post for slug ${slug}`);
  52.  
  53. // Use the exclamation operator to tell TypeScript that the value is defined
  54. return postData.post!;
  55. };
  56.  
  57. // skipped
  58. ```
Add Comment
Please, Sign In to add comment