stackuser
stackuser

Reputation: 283

How to use ternary operator to display some text instead of using if else conditions in react and typescript?

i have code like below,

if (filteredIds.length > 0) {
    notify({
        title: `${
            type === "type1"
                ? 'type1 checks'
                : 'type2 checks'
        } started.`,
    });
 } else {
     notify({
         title: `${
             type === "type1"
                 ? 'type1 checks'
                 : 'type2 checks'
         } have been already running on selected id.`,
     });
 }

the above code works. But i want to use ternary operator to be used instead of if and else as the notify thing seems to be repetitive.

i want something like having the ternary operator in notify itself to return necessary text based on filteredIds length and type.

notify({
    title: `${ //condition here
        type === "type1" 
            ? 'type1 checks'
            : 'type2 checks'
    } started.`,
});

Basically i want the if else code to be less code. Could someone help me with this. I am new to programming and not sure how to use nested ternary operator. thanks.

Upvotes: 2

Views: 687

Answers (3)

Eziz Hudayberdiyev
Eziz Hudayberdiyev

Reputation: 451

interface Result {
  title: string
}

const notify = (title: string): Result => {
  // checking condition logic
  // if (type) {
  // ...
  // }
  return {title: 'your result here'}
}

And then

notify('argument')

Upvotes: 0

benmneb
benmneb

Reputation: 2303

if/else

if (filteredIds.length > 0) {
    notify({
        title: `${
            type === "type1"
                ? 'type1 checks'
                : 'type2 checks'
        } started.`,
    });
 } else {
     notify({
         title: `${
             type === "type1"
                 ? 'type1 checks'
                 : 'type2 checks'
         } have been already running on selected id.`,
     });
 }

ternary expression

 notify({
   title: `${
     type === "type1"
       ? 'type1 checks'
       : 'type2 checks'
   } ${filteredIds.length ? 'started.' : 'have been already running on selected id.'}`,
 });

Upvotes: 1

Imanpal Singh
Imanpal Singh

Reputation: 1201

Are you looking for a conditional expression like this?

notify({
    title: `${
        type === "type1" 
            ? 'type1 checks'
            : 'type2 checks'
    } ${filteredIds.length? 'started' : 'have been already running on selected id'}.`,
});

Upvotes: 1

Related Questions