Skip to content

Instantly share code, notes, and snippets.

@madyankin
Last active April 30, 2019 05:56
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 madyankin/a2bd1a02294a38a2002b036bfc70daa7 to your computer and use it in GitHub Desktop.
Save madyankin/a2bd1a02294a38a2002b036bfc70daa7 to your computer and use it in GitHub Desktop.
Coding Guidelines

Coding guidelines

General

null and undefined

Use undefined wherever is possible. Do not use null.

Umbrella modules

Use umbrella modules (index.ts) carefully to prevent issues with cyclic imports.

Use invariants

When some optional values depend on a value, use invariants to make sure that contracts are not violated:

export interface IProps {
  isEditable?: boolean;
  onValueChange?: () => any;
}

export default class Editor extends Component<IProps> {
  public render() {
    const { isEditable, onValueChange } = this.props;

    if (isEditable) {
      invariant(
        onValueChange,
        "Editor is editable, but onValueChange is missing",
      );
    }

    // Some other code
  }
}

With invariants, we can follow a safer way to access 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:

  public render() {
    const { title, body } = this.getPost();
    // skipped
  }

  // skipped

  private getPost = () => {
    const { postData, slug } = this.props;

    // Use invariant to throw an error when the required value is undefined
    invariant(postData.post, `No post for slug ${slug}`);

    // Use the exclamation operator to tell TypeScript that the value is defined
    return postData.post!;
  };

  // skipped

JSX

Use && for conditional rendering in JSX

Correct: {foo && <Foo>{foo}</Foo>}

Wrong: {foo ? <Foo>{foo}</Foo> : null}

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