skip to Main Content

I need a type for my component. There are two fields title and description. They both can be undefined. But description cannot be without title.
Here is correct examples: <Component title='str' description='str'/> or <Component title='str'/> or <Component/> but this one is incorrect <Component description='str'/>

I try something like this

type Props = { title?: string; description?: string } | { title?: never; description?: never };

but that does not work

2

Answers


  1. Something like this should work:

    type Props = { title: string; description?: string } | {};
    

    However, since {} represents any non-nullish value rather than strictly an "empty object," you should use Record<string, never> to explicitly define an empty object type:

    type Props = { title: string; description?: string } | Record<string, never>;
    
    Login or Signup to reply.
  2. You can define the type as below:

    type Props = { title?: string } | { description?: string, title: string };
    

    TS playground:

    type Props = { title?: string } | { description?: string, title: string };
    
    const Component  = ({}: Props) => false;
    
    Component({ description: "My description" }); // Error
    Component({ title: "My title" });
    Component({ title: "My title", description: "My description" });
    Component({});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search