I've seen multiple examples of React components using Typescript:
class Foo extends React.Component<IProps, IState> {}
It seems there is no a clear convention when we don't use either the Props or the State.
People set these types as any
, null
,undefined
,{}
, , etc.This is what I've seen so far:void
class Foo extends React.Component<null, null> {}
class Foo extends React.Component<any, any> {}
class Foo extends React.Component<{}, {}> {}
class Foo extends React.Component<undefined, undefined> {}
class Foo extends React.Component<void, void> {}
class Foo extends React.Component<object, object> {}
What's the best way of doing it?
Update:
Props:
void
cannot be used (https://github.com/Microsoft/TypeScript/issues/15409 and https://github.com/Microsoft/TypeScript/issues/15419 ) as the props object is initialised to {}
SOLUTION
Simply do - class Foo extends React.Component {}
as prop and state are initialised to {}
React components can greatly benefit from TypeScript. Typing components is especially useful to validate the component props. Usually, that's performed by defining an interface where each prop has its type. Then, when the annotated component renders, TypeScript verifies if correct prop values were supplied.
Stateless components, by contrast, have no state. Note that both types of components can use props.
Components of TypeScript. The TypeScript language is internally divided into three main layers. Each of these layers is divided into sublayers or components. In the following diagram, we can see the three layers and each of their internal components.
To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.
From https://github.com/DefinitelyTyped/DefinitelyTyped/blob/15b7bac31972fbc081028937dfb1487507ca5fc9/types/react/index.d.ts#L199-L200
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Props and state are initialised to {}
, so for a component with no state nor prop we can simply do:
class Foo extends React.Component {}
As answered for this question, you can use the React.FC<{}>
class
const MyStatelessComponent : React.FC<{}> = props => <div>{props.children}</div>
Or if your markup gets bigger:
const MyStatelessComponent : React.FC<{}> = props => { {/* Some code here */} return <div>{props.children}</div> }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With