kevin
kevin

Reputation: 3488

Is there a way to make required typescript values optional if certain value is provided?

I'm trying to add a disabled feature of sorts to one of my components. Right now, all the parameter values are required. However, I'm curious if there is a way to set them all to be optional if one value is provided (like disabled?: boolean). That way, I can add my have a ternary to output my component if it's disabled, ie. has no values to show, but also retain the strict types that all need to be present in the event its not disabled.`

tldr; is there a way to make all the params below optional conditionally?

Ternary in action:

enter image description here

its interface

export interface IVideoPlayerController {
  title: string;
  author: string;
  sourceAddress: string;
  description: string;
  timeStamp: ITimeStamp;
}

Upvotes: 1

Views: 574

Answers (2)

vitoke
vitoke

Reputation: 748

Yes there is and it's quite easy using union types:

type IVideoPlayerController =
  | { disabled: true }
  | {
      disabled?: false;
      title: string;
      author: string;
    };

With this type you either pass only disabled (true), or otherwise it requires the other props, so these are all valid:

<VideoPlayer disabled />
<VideoPlayer title="abc" author="abc" />
<VideoPlayer disabled="false" title="abc" author="abc" />

And these are not valid:

<VideoPlayer />
<VideoPlayer title="abc" />
<VideoPlayer disabled="false" />

Here is a CodeSandbox with that allows you to play with how it works.

Upvotes: 1

xpertdev
xpertdev

Reputation: 1433

if you face a scenario in which you don't have values for strongly typed components. then Don't mix the concern's.

You should create a another separate component which show the NoVideoPlayerContent Component when there is no title author etc. and one the existing you have which shows the VideoPlayer content when there is title and all the other props.

I always prefer AHA Programming technique Over DRY. Which means avoid hasty abstractions.

the other way you can do is to add undefined in the props like

title: string |undefined 

and have a checks in the VideoPlayer Component.

{Boolean(title) && (
// show content
)}

{!Boolean(title) && (
// show loader or some text
)}

Upvotes: 0

Related Questions