首页 > 解决方案 > 如何使用三元运算符显示一些文本,而不是在反应和打字稿中使用 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.`,
     });
 }

上面的代码有效。但是我想使用三元运算符而不是 if 和 else 因为通知的事情似乎是重复的。

我想要一些东西,比如让三元运算符通知自己根据过滤后的长度和类型返回必要的文本。

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

基本上我希望 if else 代码更少。有人可以帮我解决这个问题。我是编程新手,不知道如何使用嵌套三元运算符。谢谢。

标签: reactjstypescript

解决方案


您是否正在寻找这样的条件表达式?

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

推荐阅读