Discriminated Unions in TS

Discriminated Unions in TS

A discriminated union in typescript is a a feature that allows you to create variations of a type that shares a union.

example:
// create a shared interface between the two types
interface SharedBioProps {
  src?: string;
}

// create one interface for component with children of type ReactNode and text and title of type never 
interface BioWtihChildren extends SharedBioProps {
  children: React.ReactNode;
  title?: never;
  text?: never
}

// create one interface for component with children of type never and text and title of type ReactNode 
interface BioWithTitleAndText extends SharedBioProps {
  children?: never;
  title: string
  text: string;
}

// here we create the discriminated union. 
type BioProps = BioWtihChildren | BioWithTitleAndText;

export default BioProps;
// here we import the type and us as our props interface in our react app
import BioProps from './bioProps.ts'
function BioComonent(props: BioProps) {
  const { src = "", title, text, children } = props;
  return (
    <article>
      {src && (
          <Avatar
            src={src}
          />
      )}

      {children ? (
        children
      ) : (
        <div>
          <h3>{title}</h3>
          <p>{text}</p>
        </div>
      )}
    </article>
  )
}