Posts Default Props in React and Typescript
Post
Cancel

Default Props in React and Typescript

Lately I started to do some frontend related stuff and started working with React. At the start when using JS I was using PropTypes for typechecking. When using Proptypes it is easy to create optional properties you just need to add them to defaultProps. Later I switched to typescript to get better type checks in the whole codebase and a better developer experience. But when I came to the point where I needed to have an property with some default I could not find any easy to understand solution. But today I found a easy solution on this GitHub issue, for Typescript 3.1 or above. The following example shows you how to make a default property in React with Typescript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React from 'react';

interface Props {
  greeting?: string
  planet: string
}

const Greet = (props: Props) => {
  const { greeting, planet } = props;

  return (
    <p>
      {`${greeting} from ${planet}`}
    </p>
  );
};

Greet.defaultProps = {
  greeting: 'Hello',
} as Partial<Props>;

const component = <Greet planet="Earth" />

The as Partial<Props> is not necessary but it is a good practice as without it you could use wrong type as a default prop and TypeScript wouldn’t complain.

References

Resources

This post is licensed under CC BY 4.0 by the author.