我是Typescript的新手,不知道如何检查一个字符串参数是否为NULL。null
或不。
该。concat
下面的函数被导出供其他Typescript模块使用。我想生成一个错误信息,如果任何一个字符串参数是 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');
})
});
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
.
手稿 是 具有可选类型断言和检查分层的Javascript。您可以检查 null
以完全相同的方式。
但是Typescript给了你另一个选择:不支持 null
的,这就是你的函数的参数声明。事实上,你的函数的参数声明已经做到了这一点。(a: string, b: string)
意味着两个 a
和 b
只能是字符串,不能是 null
.
例如,如果你把它改成 (a: string | null, b: string)
这意味着 a
可以是空的,尽管 b
还是不行。
所以如果你保持你的函数参数的方式,你就不需要再做一次 null
检查。如果你想允许空值,那么你需要添加 | null
的类型断言。
也就是说,如果你希望你的库的其他用户将使用Javascript而不是Typescript,并且你想防止他们把 null
那么你就会保留null检查,即使它们对Typescript来说是多余的。
让我知道我是否正确理解了你的问题。