DEV Community

Cover image for Default Props in React/TS - Part Deux

Default Props in React/TS - Part Deux

Adam Nathaniel Davis on June 21, 2020

A few days ago, I posted a long article about my struggle to find a solution for setting default prop values in React/TS components. Based on feed...
Collapse
 
mlavoiedev profile image
mlavoiedev

Hi Adam,

It's my first time commenting here but I came across the same problem last week and I wanted to share my solution with you.

type MyComponentProps = {
  // Required
  requiredNumberProp: number;

  // Not required
  booleanProp?: boolean,
  stringProp?: string,
}

// We need the Partial notation so we don't have to declare required props
const DEFAULT_PROPS: Partial<MyComponentProps> = {
  booleanProp: true,
  stringProp: 'FOO',
};

const MyComponent = (props: MyComponentProps) => {
  // We're spreading DEFAULT_PROPS before actual props to overide them with the real ones
  const {
    requiredNumberProp,
    booleanProp,
    stringProp,
  } = { ...DEFAULT_PROPS, ...props }; 

  // We still need to validate stringProp before using the split() method
  //  But that's ok !
  //  Because if we use this component, we can totally do something like this :
  //  <MyComponent requiredNumberProp={42} stringProp={undefined} />
  //  So Typescript is right, we need to validate that the value is a string

  const splitText = stringProp ? stringProp.split('') : [];

  return `...`
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

I certainly appreciate your input. And if this solution works for you, then... great! But I have to say that, for me, there is one key aspect that basically falls short. It's in this:

  // We still need to validate stringProp before using the split() method
  //  But that's ok !
  //  Because if we use this component, we can totally do something like this :
  //  <MyComponent requiredNumberProp={42} stringProp={undefined} />
  //  So Typescript is right, we need to validate that the value is a string

  const splitText = stringProp ? stringProp.split('') : [];

Again, if that works for you, then... awesome! But I personally think this makes no sense. And it is part of the frustration I had in working through this problem.

If I have a prop - let's say it's X - and that prop is listed as an optional prop, of type string, then, with no further information, I understand why we need to validate whether X is of type string before we perform a .split() on it. This makes sense because the X variable could be a string OR it could be undefined.

But if that optional prop also has a default value set, then it makes no sense that I have to validate its data type before doing a .split(). Because the variable can never be undefined! If a value was provided in the prop, then TS is supposed to be ensuring us that this value was a string (and can thus be .split()). And if a value was not provided in the prop, then we know that the default value will be used - which is a string - and can be .split().

This is the heart of my (massive) frustration with this shortcoming in TS. If I've defined X as type string and I've provided a default string value, then I should never again have to validate that the prop value is, in fact, a string.

It will ALWAYS be a string. And it will NEVER be undefined.

Collapse
 
mlavoiedev profile image
mlavoiedev • Edited

Yeah I just understood that my DEFAULT_PROPS will not act as fallback values. My bad :( ! I did more research after thinking about that. What do you think of Typescript official solution to the problem ?

typescriptlang.org/docs/handbook/r...

function Greet({ name = "world" }: Props) {
    return <div>Hello {name.toUpperCase()}!</div>;
}
Thread Thread
 
bytebodger profile image
Adam Nathaniel Davis

I have several problems with their "official solution".

First, as stated in my previous rebuttals, this approach still wipes out the props namespace. In fact, look at their example. I think it kinda makes my case for me.

How many times have you had some function inside your component where there's a variable called something generic - like "name"?? And that's fine - but what if you also had a prop that was passed in called "name". Now you run into naming collisions. Because "name" is defined at the component level. So if you try to set something else as "name", you end up overwriting your props.

But if you have props.name, then you can always set some other variable to "name", secure in the knowledge that the props will always live under props.name.

The "official solution" also falls down if you want to use anything more than simple types. For example, what if you want to use a union type???

Imagine that "name" can be a string (like "Adam Davis") or an object (like, for example: {firstName: 'Adam', lastName: 'Davis'}. But there's no way to annotate that in the example above. You're stuck just using inference to determine the data type - and if you're gonna do that, might as well stick with JS.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Also, I'll note that, for me at least, I don't "like" these kinds of solutions because (as I outlined in some parts of my article), I really appreciate the fact that, in "old skool" React/JS, the props are all inside the props object. I realize now, after talking to other "TS-types", that some people really don't care much about this. But for me, it's very important.

I really value the ability to simply read through code and know, on first read, that this value comes from props and this other value comes from some where else. And how do I know that just by reading a line-or-two of code? I know it because the prop values have props.xxxx right in their name.

Granted, in my "final solution", the props are shunted into another object - which I've called args. But the difference is semantic. The important point is that my props remain in an object namespace that clearly defines them as coming from the props.

Collapse
 
timdev profile image
Tim Lieberman

Unless I'm missing something, this can be simplified considerably if you're willing introduce a second variable inside your component to hold the props-with-defaults-applied. Have you considered something like:

import {PropsWithChildren} from 'react';

interface FooProps {
  id: number;
  email: string;
  nickname?: string;
}

const FooComponent = (propArgs: PropsWithChildren<FooProps>) => {
  // Our *actual* props
  const props = { ...{nickname: 'Anonymous Coward'}, ...propArgs };

  // Since we're referencing `props` and not `propArgs`, typescript
  // correctly infers that props.nickname is defined and is a string.
  console.log(props.nickname.split(' '));
}

FooComponent({id: 5, email: 'foo@example.com'}); 
// => [  'Anonymous', 'Coward' ]
FooComponent({id: 10, email: 'bar@example.com', nickname: 'Max Power'}); 
// => [ 'Max', 'Power' ]
Enter fullscreen mode Exit fullscreen mode

?

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Hmm... When I was going through this headache in June, I tried about 1,000 different things. But I don't think I specifically tried this. I do like leveraging the multiple-spread-operator approach to first set default values - and then overwrite them if they were provided in propArgs. I do this when I'm setting style attributes with CSS-in-JS.

I'm not seeing any downside to this approach at the moment. And it doesn't require any helper function/Hook.

Awesome!

Collapse
 
micmor profile image
Michael Morawietz

Hi,
TypeScript should make work easier, not harder. Although I find your article really interesting, your solution is really much too complex for me. Seems like React and Typescript don't really belong together. The best solution I have found so far is this one : /* eslint-disable react/require-default-props */. Short and painless.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

The best solution I've found so far isn't even the one outlined in this article. It's the one suggested by Tim Lieberman just above in the comments. However, the fact that it took me two articles to find that solution, and the fact that it's nowhere-near intuitive for someone who's just trying to switch from React/JS to React/TS, annoys me about how some things that are dead simple in React/JS can become incredibly convoluted in React/TS.

Collapse
 
micmor profile image
Michael Morawietz

But still, you showed me what's possible, thank you.

Collapse
 
ecyrbe profile image
ecyrbe

Hi Adam,

You may want to try this :

type Optionals<T extends object> = Required<Pick<T, Exclude<{
    [K in keyof T]: T extends Record<K, T[K]> ? never : K
}[keyof T], undefined>>>;

function setDefaults<Props extends object>(props: Props, defaults: Optionals<Props>): Required<Props> {
    return Object.assign({ ...props }, ...Object.keys(defaults).map(key => ({ [key]: props[key] ?? defaults[key] })));
}
Enter fullscreen mode Exit fullscreen mode

it's shorter, delegates type checking of optionals to the type Optionals<T>. I suggest you try the code to understand it. it needs typescript 3.8 (worth upgrading for ?. and ?? operators ).

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Thank you! Since I'm new to the TS stuff, your solution looks a bit gobbledy-gookish to me at first, so I'll definitely look at it carefully to make sure that I truly grok it before putting it in. But this looks very promising!

And we are already using TS 3.8.3 - so ? and ?? operators shouldn't be a problem.

Cheers!

Collapse
 
ecyrbe profile image
ecyrbe • Edited

Yes, the hardest part is this one :

{ [K in keyof T]: T extends Record<K, T[K]> ? never : K }
Enter fullscreen mode Exit fullscreen mode

Witch means, return me an object type that has the same properties as Props, but with property types equal to the property name if the underlying property is not required .
then :

{ [K in keyof T]: T extends Record<K, T[K]> ? never : K }[keyof T]
Enter fullscreen mode Exit fullscreen mode

that means return me a union of all the optional properties names of Props.

Then the idea is to have setDefaults(), not compile if you try to pass default parameters not declared in Props, or if you forgot to add defaults that where declared optional in Props.

This is where you will thank typescript for having your back everytime you forgot to handle a default parameter, because typescript will catch it.

Thread Thread
 
bytebodger profile image
Adam Nathaniel Davis

Excellent stuff. And thank you(!) for the extended explanation. I've been coding for 20+ years and I've done plenty of generics in languages like C#. But when you're in a "JavaScript mindset", it can still take a little bit to get your head back in that mindspace.

All though I'm generally a big fan of generics, when you haven't been working with them for awhile, code like that above can look like the first time that you dove into regular expressions.

Cheers!

Collapse
 
anuraghazra profile image
Anurag Hazra

What's wrong with Component.defaultProps = {}??

Or you are just digging into rabbit hole for educational purposes?

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

From the article above, Requirement #7:

I don't wanna use any solutions that are in imminent danger of being deprecated. (This is why I'm not using the native defaultProps feature that currently ships with React. There's a lot of chatter about removing this feature for functional components.)

I also discussed the presumed deprecation plans in the previous article.

Collapse
 
anuraghazra profile image
Anurag Hazra

Ohh I see, okay this makes sense. :D