大家好
我想請問TypeScript能檢驗後端傳來的資料格式嗎?
我的前端使用的是vue3、vite,code是這樣。
設定了一個const theAxios = ref<string>()的字串變數去接後端的資料
const theAxios = ref<string>()//字串變數
axios.get('http://localhost/typescriptTest/returnNumber.php')
.then((res)=>{
    let data = res.data
    
    theAxios.value = data    
})
.catch((error)=>{
    console.log('error');
})
但是如果php回傳的是數字30000000時
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept');
echo 30000000;
結果是不會報錯誤。不過變數theAxios,變成了number格式.......
我很擔心之後做TypeScript專案時,會有問題,所以想請問大大們。
還是只能自行用typeof確認回傳的格式呢?
TypeScript 主要是在開發階段檢查資料型別, 經過 [vue-tsc --noEmit && vite build] 後出來的 production runtime,已經不會有 type 參與了, 型別都會被移除掉
假如真的需要檢查外部API過來的資料型別,可以利用 typeof
axios.get('http://localhost/typescriptTest/returnNumber.php')
.then((res)=>{
    let data = res.data
    if (typeof data !== 'string') {
     return Promise.reject('error')
    }
    theAxios.value = data    
})
.catch((error)=>{
    console.log('error');
})
以zod舉例:
// 定義API schema
const userSchema = z.object({
  id: z.string().uuid(),
  name: z.string()
  login_count: z.number()
})
// 可將 zod 的 schema 透過z.infer轉為Typescript 的type來使用
const type User = z.infer<typeof userSchema>
axios.get('http://localhost/user/1')
.then((res)=>{
    let data: User = res.data
    let parsed = userSchema.safeParse(data) 
    //safeParse 會在schema不符合時回傳一個 object, 包含錯誤訊息, 不會直接噴exception
    if (parsed.success) {
        theAxios.value = parsed.data
    } else {
        return Promise.reject(parsed.error)
    }     
})
.catch((error)=>{
    console.log('error');
})
// axios.get('http://localhost/user/1')
// .then((res)=>{
//    let data: User = res.data
//    let parsed = userSchema.parse(data) 
//      // parse 會在schema不符合時噴exception
//    theAxios.value = parsed
// })
// .catch((error)=>{
//    console.log('error');
// })