Typecscript:如何检查字符串是否为NULL

问题描述 投票:0回答:2

我是TS的新手,正在寻找一种方法来确定如何查找我的输入字符串是否为null。

我目前正在使用以下代码。我将变量concat导出到差异TS。我想发布一条错误消息是我的字符串为NULL。

    export const concat = (a: string, b: string) => {
     //if ((typeof a === null) || (typeof b === null)) { throw new Error(' A is missing')}
     **//if ((a === '') || (b === '')) { throw new Error(' A is missing')}**
           return a.concat(b);
    }

describe ('concat', () => {

  it('Should concat these two strings', ()=> {
    const result=concat('He','llo')
    expect(result).to.equal('Hello');
  })
});
typescript null export concat
2个回答
1
投票
    export const concat = (a: string, b: string) => {
     if ((a == null) || (b == null)) { throw new Error('A is missing')}

     if ((a === '') || (b === '')) { throw new Error('A is missing')}

           return a.concat(b);
    }

只需删除typeof。使用==可以检查输入是null还是undefinded


1
投票

Typescript is具有可选类型断言和分层检查的Javascript。您以完全相同的方式检查null

但是Typescript为您提供了另一个选择:首先禁止null。实际上,这就是函数的参数声明已经执行的操作:(a: string, b: string)表示ab都只能是字符串,而不能是null

例如,如果将其更改为(a: string | null, b: string),则意味着a可以为空,尽管b仍然不能为空。

因此,如果您以自己的方式保留函数的参数,则无需进行null检查。如果要允许空值,则需要在类型断言中添加| null

话虽如此,如果您希望库中的某些其他用户将使用Javascript而不是Typescript,并且要防止他们传入null,那么您将保留null检查,即使它们对于打字稿。

让我知道我是否正确理解了您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.