Argument of type ‘string | string[]‘ is not assignable to parameter of type ‘string‘.<br/>Type ‘stri

原来代码:
totalCount是number,result.value我期望是string,

 TextPickerDialog.show({
    
    
              range:['5','10','15','20','25'],
              value:this.totalCount.toString(),
              onAccept:(result)=>{
    
    
              
                  this.totalCount = parseInt(result.value);
                
              }

TypeScript 有时会因为类型推断而报错,尤其是当类型声明不够明确时,这里result.value的可能类型为string|string[],TypeScript无法保证是string类型,所以通过类型断言来强制为 string

 TextPickerDialog.show({
    
    
              range:['5','10','15','20','25'],
              value:this.totalCount.toString(),
              onAccept:(result)=>{
    
    
                if (typeof result.value === 'string') {
    
    
                  this.totalCount = parseInt(result.value);
                }
              }

现在可以正常显示了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44628096/article/details/141997095