【问题标题】:Why concatenating string and undefined does Not raise an error in TypeScript为什么连接字符串和未定义不会在 TypeScript 中引发错误
【发布时间】:2023-02-18 15:42:06
【问题描述】:

例如,此代码无效:

function fn1(a: number, b?: number) {
    console.log(a + b);  // error 'b' is possibly 'undefined'.(18048)
}
fn1(5);

但是这段代码是有效的:

function fn2(a: string, b?: string) {
    console.log(a + b);  // valid code
}
fn2('Hi');

为什么严格模式下的 TS 在第二种情况下不引发错误?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    它不会引发错误,因为在打字稿中,允许将字符串与字符串类型的可选参数连接起来,其中包括未定义。这是因为 TypeScript 认为可选参数如果未定义将被视为空字符串,

    【讨论】:

      【解决方案2】:

      因为在连接中,如果第一个值是string,JavaScript 将强制第二个值是string,这就是为什么你可以用string连接任何东西。

      但是,如果您尝试创建 number 类型的 a,或尝试任何其他操作,则会发生错误:

      function fn2(a: number, b?: string) {
          console.log(a + b);  // 'b' is possibly 'undefined'
      }
      fn2('Hi');
      

      【讨论】:

        猜你喜欢
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 2020-12-21
        • 2012-10-19
        相关资源
        最近更新 更多