1、js常规类型转换

https://www.cnblogs.com/123525-m/p/15788443.html

https://blog.csdn.net/allway2/article/details/124955087

2、vue 强类型转强类型

自定义强类型:

  declare type ComponentOptions = {
    label?: string
    value?: FormValueType
    disabled?: boolean
    key?: string | number
    children?: ComponentOptions[]
    options?: ComponentOptions[]
  } & Recordable
declare type FormValueType = string | number | string[] | number[] | boolean | undefined | null

declare type Recordable<T = any, K = string> = Record<K extends null | undefined ? string : K, T>

type Record<K extends keyof any, T> = {
    [P in K]: T;
};
declare type BillingHandlingData = {
  BillingHandlingId: number
  ItemCode: sting | number | undefined
}
 

const ChargeTypeArr = reactive([]) //默认:never[]
const CapacityTypeArr = reactive([] as ComponentOptions[])  //定义ComponentOptions类型
const Arr1 = reactive([])

const getDictionaryList = async () => {
  const ids = [18, 27, 28, 29]
  const res = await getDictionaryListByIdsApi(ids)
  ChargeTypeArr.length = 0
  CapacityTypeArr.length = 0
  Arr1.length = 0
  if (res.data !== null && res.data.length > 0) {
    for (let i = 0; i < res.data.length; i++) {
      let temp = res.data[i]
       if (temp.TypeId == 29) {
        ChargeTypeArr.push({ value: temp.Dkey, label: temp.Dvalue })//提示但不报错:不能将类型“string”分配给类型“never”。
      } else if (temp.TypeId == 18) {
        CapacityTypeArr.push({ value: temp.Dkey, label: temp.Dvalue })//不提示
      }
    }
    if (CapacityTypeArr.length > 0) {
    //报错:不能将类型“FormValueType”分配给类型“string | undefined”。不能将类型“null”分配给类型“string | undefined”。
      formData.value.ItemCode = CapacityTypeArr[0].value 
      console.log(‘x1’, CapacityTypeArr)
      console.log(‘x2’, CapacityTypeArr[0].value) 
     //方案一:
     //当CapacityTypeArr的value是int类型时可行
      console.log(‘0’, parseInt(CapacityTypeArr[0].value))
      console.log(‘1’, CapacityTypeArr[0].value as any)//任意类型
    // 当CapacityTypeArr的value是string类型时可行
      console.log(‘2’, CapacityTypeArr[0].value as string)
      console.log(‘3’, CapacityTypeArr[0].value + ”) 
      console.log(‘3’,String( CapacityTypeArr[0].value))
    //方案二  重新定义一个ComponentOptions2,修改value的类型
    //方案三 不使用强类型
    formData.value.ItemCode = ChargeTypeArr[0].value  //仅提示但不报错: 类型“never”上不存在属性“value”。
 对于小、中型项目,强类型校验,增加复杂度、工作时间,不划算。加一个判断就能避免报错了
      if (Arr1.length > 0 &&isNaN(Arr1[0])) {
        formData.value.ItemCode = Arr1[0].value
      }
 

    }
  }
}
 
 
 

原文地址:http://www.cnblogs.com/hao-1234-1234/p/16784104.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性