How to extend type union props to a react class component?

Viewed 91

I have two props showAccountName and accountType. accountType is required only when showAccountName is true. When showAccountName is false, accountType is not required.

So, I used a type union -

type AccountProps = 
| { showAccountName?: false; accountType: never; }
| { showAccountName?: true; accountType: string; }

and trying to extend these props in a class component

class UserAccount extends React.PureComponent<AccountProps> 
{ .... }

But I am unable to access showAccountName or accountType using this.props in UserAccount. Any idea what I am doing wrong here? Or is there any other way to make one prop mandatory based on another optional prop? (without using type) I am new to typescript, any help is much appreciated!

1 Answers

Instead of making showAccountName an optional prop in both cases, only make it optional for the case where it should be falsy (and also just omit the other prop in that case):

{ showAccountName?: false; }

and in the case where you want it to be shown, make both props non-optional:

{ showAccountName: true; accountType: string; }

So, together, it looks like this:

import {default as React} from 'react';

type AccountProps = 
  | { showAccountName?: false; }
  | { showAccountName: true; accountType: string; };

class UserAccount extends React.PureComponent<AccountProps> {
  render () {
    return (
      <div>
        {this.props.showAccountName ? this.props.accountType : 'Account type not shown'}
      </div>
    );
  }
}

TS Playground

Related