This document will show a compilation of resources showing what are proper coding standards and best practices when building a large Typescript React project.
Annotate arrays as string[]
as opposed to Array<string>
. As it is easier to read and it is used by the Typescript team.
- Don't use Classes-related OOP.
- Stuff like
protected
,private
,public
,implements
- Abstract classes
- Avoid using generics, unless you can have a good reason for using them.
- Don't use them, favor
import
, andexport
with file separation.
- Favor interfaces over types, read about differences in the handbook
- Don't use over interfaces, unless you have a good reason for doing so.
- Favor Union types over type hierarchies when you need to constrain values.
No need to use constructor
inside Class components
Don't:
type State = { count: 0 };
type Props = {};
class Counter extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
count: 0,
};
}
}
Do:
type Props = {};
class Counter extends Component<Props> {
state = {
count: 0,
};
}
Always Provide explicit type for children
props
Don't
// Button.tsx
import React, { Component } from 'react';
class Button extends Component {
render() {
const { children } = this.props;
return <button>{children}</button>;
}
}
// App.tsx
import React, { Component } from 'react';
import Button from './components/Button';
const App = () => {
render() {
return (
<Button>
Click me!
</Button>
);
}
}
Do:
// Button.tsx
import React, { Component, ReactNode } from 'react'; // ReactNode is provided by @types/react as type
type Props = {
children: ReactNode,
}
class Button extends Component<Props> {
render() {
const { children } = this.props;
return <button>{children}</button>;
}
}
// App.tsx
import React, { Component } from 'react';
import Button from './components/Button';
const App = () => {
render() {
return (
<Button>
Click me!
</Button>
);
}
}
- When you need a constraint set of 2+ possible values, favor
Enums
heavily. - Prefer string enums over implicit enums if the value is relevant.
enum Colors {
Red = 'Red',
Green = 'Green',
Blue = 'Blue'
}
type Props = {
colors: Colors
}
Don't:
SkaterBoy.tsx
userAccessHandlers.ts
Do:
skater-boy.tsx
user-access-handlers.ts