【问题标题】:Passing in boolean and returning a string in TypeScript传入布尔值并在 TypeScript 中返回一个字符串
【发布时间】:2020-11-18 03:46:17
【问题描述】:

我正在努力解决 TypeScript 中的一个问题,我想知道是否有人可以帮助我。 任何人都可以帮忙吗?我目前正在学习 TypeScript,最初想到的是使用 if/else 语句或 switch 语句。

问题:完成接受布尔值的方法,如果为真则返回“YES”,如果为假则返回“NO”。

export const boolToWord = (bool: boolean): string => {
  throw new Error("Not implemented!");
};

这是我想出的第一个解决方案是使用 if/else 语句,但它不起作用。

export const boolToWord = (bool: boolean): string => {
 if(true){
    return "Yes"
 } else if (false) {
    return "No"
 } else if {
   return "Not Implemented"
 }
};
boolToWord(True);

我也尝试过使用 switch 语句,但是没有用。

export const boolToWord = (bool: boolean): string => {
  switch(boolean){
    case: true;
    console.log("YES");
    break;
    case: false;
    console.log("NO");
    break;
    case: error;
    console.log("Not Implemented")
    break;
   }
};
boolToWord(True);

【问题讨论】:

    标签: string typescript boolean


    【解决方案1】:

    这是你想要的吗?

    return bool ? 'YES' : 'NO';
    

    【讨论】:

    • 是的。如果传递的布尔值为真,那么我希望它返回“YES”。如果布尔值是假的,那么我希望它返回“NO”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2022-10-26
    • 2011-05-06
    • 2017-07-08
    • 2021-10-22
    相关资源
    最近更新 更多