Home > Back-end >  Make type accept a property one of 4 sets
Make type accept a property one of 4 sets

Time:09-02

Here's my code:

interface Props<T> {
  config: {
    title?: string,
    (
      limitText: boolean,
      bold: boolean,
      content: ReactNode
    )
    | (iterable: boolean, content: T[], selector: string)
    | (markup: boolean, content: string)
    | (stack: boolean, coloredLevel?: boolean, content: string[])
  }
}

What I'm trying to achieve is for config to accept title, and one of the other 4 types. How can I achieve this? I was thinking smth like discriminatory union type deal.

ts playground

CodePudding user response:


interface PropsBase<T> {
  config: {
    title?: string,
  }
}

interface Props1 extends PropsBase<unknown> {
    config: {
      title?: string,
      limitText: boolean,
      bold: boolean,
      content: 'ReactNode'
    }
}

interface Props2<T> extends PropsBase<T> {
    config: {
        title?: string,
        markup: boolean,
        content: T,
    }
    
}

interface Props3 extends PropsBase<unknown> {
    config: {
        title?: string
        stack: boolean,
        coloredLevel?: boolean,
        content: string[]
    }
}

type Props<T> = Props1 | Props2<T> | Props3;
  • Related