类型推论
1.定义字段imgs是由ImgsData类型组成的数组
2.定义字段imgobj是由ImgsData类型组成的对象
import { PropType } from 'vue'
import { ImgsData } from '@/interface'
export default defineComponent({
props: {
imgs: {
type: Array as PropType<ImgsData[]>,
default: () => []
},
imgobj: {
type: Object as PropType<ImgsData>,
default: () => []
},
},
})
interface.ts
export interface ImgsData {
attachmentName: string
attachmentOrder: number
attachmentUrl: string
}
类型断言
/*
类型断言(Type Assertion): 可以用来手动指定一个值的类型
语法:
方式一: <类型>值
方式二: 值 as 类型 tsx中只能用这种方式
*/
/* 需求: 定义一个函数得到一个字符串或者数值数据的长度 */
function getLength(x: number | string) {
if ((<string>x).length) {//如果x是string类型,执行这条,否则执行下面的条件
return (x as string).length
} else {
return x.toString().length
}
}
console.log(getLength('abcd'), getLength(1234))