1、js常规类型转换
https://www.cnblogs.com/123525-m/p/15788443.html
https://blog.csdn.net/allway2/article/details/124955087
2、vue 强类型转强类型
自定义强类型ComponentOptions,用来接收所有Options选项数据。
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; }; 自定义数据类型BillingHandlingData declare type BillingHandlingData = { BillingHandlingId: number ItemCode: sting | number | undefined } const CapacityTypeArr = reactive([] as ComponentOptions[]) //定义ComponentOptions类型 const Arr1 = reactive([]) //默认:never[] const getDictionaryList = async () => { const ids = [18, 27, 28, 29] const res = await getDictionaryListByIdsApi(ids) 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 == 18) { CapacityTypeArr.push({ value: temp.Dkey, label: temp.Dvalue })//不提示 Arr1.push({ value: temp.Dkey, label: temp.Dvalue })//提示但不报错:不能将类型“string”分配给类型“never”。 } } if (CapacityTypeArr.length > 0) { //报错:不能将类型“FormValueType”分配给类型“string | undefined”。不能将类型“null”分配给类型“string | undefined”。 formData.value.ItemCode = CapacityTypeArr[0].value console.log('ItemCode', formData.value.ItemCode) console.log('x1', CapacityTypeArr) //方案一: //当CapacityTypeArr的value是number类型时可行 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的类型修改为 number //方案三 不使用强类型 formData.value.ItemCode = ChargeTypeArr[0].value //仅提示但不报错: 类型“never”上不存在属性“value”。 对于小、中型项目,强类型校验,增加复杂度、工作时间,不划算。加一个判断就能避免报错了 if (Arr1.length > 0 &&isNaN(Arr1[0])) { formData.value.ItemCode = Arr1[0].value } } } } 标签:类型转换,CapacityTypeArr,vue,console,string,number,value,类型,转强 From: https://www.cnblogs.com/hao-1234-1234/p/16784104.html