0

I recently found a way to set default props on React components, like this:

type Props = {
  children: any,
  color?: keyof typeof textColors,
};

const GTitle: React.FC<Props> = ({ children, color }) => (
  <Title color={textColors[color]}>
    {children}
  </Title>
);

GTitle.defaultProps = {
  color: 'primary',
};

The problem is that even if I define that there is a default property, the TypeScript keeps accusing the possibility of having an undefined value, as in the example below:

enter image description here

5
  • 4
    Use actual default arguments, TypeScript understands them just fine: = ({ children, color = "primary" }) => Commented Aug 15, 2022 at 12:55
  • 2
    Indeed, defaultProps will eventually go away. Commented Aug 15, 2022 at 12:57
  • 1
    check this similar question Type 'Key' cannot be used to index type 'Object' could be related to your issue. good luck ;) Commented Aug 15, 2022 at 13:00
  • Really helpful comments, thanks guys! Commented Aug 15, 2022 at 13:01
  • 1
    I think that it would be good if someone turns the comment into an answer (maybe @TchiteuMargiela?). That way this question can be marked as solved. Commented Aug 15, 2022 at 17:16

1 Answer 1

2

I managed to solve it using default arguments. TypeScript understands them just fine:

type GTitleProps = {
  children: any,
  color?: keyof typeof textColors,
};

const GTitle: React.FC<GTitleProps> = ({
  children,
  color = 'primary',
}) => (
  <Title color={textColors[color]}>
    {children}
  </Title>
);

export default GTitle;

Addendum: defaultProps will be deprecated for function components.

Sign up to request clarification or add additional context in comments.

3 Comments

Typescript understands them but not eslint.
@SalahAdDin With default rules? with me, eslint did not point out anything wrong
I found the eslint precise rule we need to use for default arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.