[英]Type checking in separate function not working in typescript
我在单独的 function 中验证参数类型,但它仍然给出以下错误 -
Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
代码是这样的-
function paramValidator(param?: string){
if(param===undefined){
throw new Error('parameter missing');
}
}
function xyz(a: string){
console.log(a);
}
function abc(a?: string){
try{
paramValidator(a);
// Working Fine
// if(a===undefined){
// throw new Error('parameter missing');
// }
xyz(a); //This line is throwing error
}
catch(e){
console.log('Error');
}
}
我想将验证逻辑放在单独的 function 中以获得更简洁的代码。 如何强制在验证后定义参数?
解决方案是使用xyz(a!)
,因为它将强制定义参数。 我们已经在另一个 function 中验证了该类型,因此在调用 function 时不需要这样做。
如果参数实际上是一个字符串,则可以返回 true 并将其用作条件
function paramValidator(param?: string): param is string {
if(param===undefined){
throw new Error('parameter missing');
}
return true;
}
function xyz(a: string){
console.log(a);
}
function abc(a?: string){
try{
if (paramValidator(a)) {
xyz(a);
}
}
catch(e){
console.log('Error');
}
}
是因为你用?
可选运算符告诉 function 在执行期间它可能可用,这取决于您是否在abc
function 中发送它。 因此,在未使用该参数调用 time 方法之前,它变得undefined
。
对于这种情况,您可以在方法中分配回退,即默认参数值。 如果您可以默认分配值,我不确定为什么需要验证器,最好有空字符串而不是未定义的东西。
function paramValidator(param?: string){
if(param===undefined){
throw new Error('parameter missing');
}
}
function xyz(a: string){
console.log(a);
}
function abc(a: string = ''){
try{
paramValidator(a); // now you don't need to call it
// Working Fine
// if(a===undefined){
// throw new Error('parameter missing');
// }
xyz(a); //This line is throwing error
}
catch(e){
console.log('Error');
}
}
此外,当您有与之关联的对象和属性时,请尝试使用??检查它们的属性。 将 null|undefined 属性设置为默认值,因此您不会期望应用程序中出现任何不良行为。
我认为将您的 try catch 块放在 if 块中将修复错误。因为参数验证器正在等待一个字符串,而您正在向它传递一个可能的未定义或字符串值。
function abc(a?: string){ if(a){ try{ paramValidator(a); // Working Fine // if(req.a===undefined){ // throw new Error('parameter missing'); // } xyz(a); //This line is throwing error } catch(e){ console.log('Error'); } } }
正如Aprova Chikara所描述的,这是对您的问题的一个很好的解释和出色的解决方案。 但是如果你想坚持你的代码并且不改变它的结构,你可以保持你的基本代码如下,只做2个微小的改变:
function paramValidator(param?: string):string{
if(param===undefined){
throw new Error("parameter missing");
}
return param;// 1
}
function xyz(a: string){
console.log(a);
}
function abc(a?: string){
try{
a = paramValidator(a) // 2
xyz(a); //Now, this line is not throwing error!
}
catch(e){
console.log('Error');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.