Vue TypeScript Starter kit

ทำไมต้อง TypeScript
Typescript ทำหน้าที่คอยเช็ก type ที่เรากำหนดให้กับตัวเเปรหรือ return type ของ method ที่เราสร้าง เพื่อไม่ให้ผิดเพี้ยนไปจากค่าที่เรากำหนด
จากตัวอย่างเราจะเห็นว่าเรามีตัวแปรชื่อว่า count ที่กำหนด type number เเละกำหนดค่าให้ตัวแปร count เท่ากับ 1 จากนั้นเราลองเปลี่ยนเเปลงค่าให้กับ count เท่ากับ “1” ที่เป็น type string ตัว typescript จะเเจ้งเตือนว่าเราไม่สามารถกำหนดค่าที่เป็น string ไปใส่ type number ได้ดังรูป
อีกหนึ่งตัวอย่าง เรามี method ชื่อ calculate ที่ return ค่าเป็น number เเละรับ parameter ชื่อ a และ b เรากำหนดให้ type เป็น number
ถ้าเราส่งค่าให้กับ function ไม่ถูกต้องตามที่เรากำหนดไว้ เจ้าตัว typescript ก็จะเเจ้งเตือนเราดังรูป
มาเริ่ม Vue + Typescript กันเถอะ
เริ่มเเรกเราต้องสร้าง project ของเราขึ้นมาก่อน โดยเราจะทำการสร้าง project ของเราผ่าน vue-cli ใช้คำสั่ง vue create “ชื่อโปรเจกต์ที่เราต้องการ” ให้เรากำหนดดังนี้
ส่วนการ setup หลังจากนี้เเล้วเเต่ความชอบของเเต่ละคนครับ เมื่อทำการสร้าง project สำเร็จ เราก็สามารถกำหนด typeให้กับ props, data, หรือ method ต่าง ๆ ได้เเล้ว เเละสามารถสร้าง folder “models” เพื่อใช้สำหรับเก็บ interface เพื่อใช้ภายใน project ของเราได้อีกด้วย
หวังว่าบทความนี้จะเป็นประโยชน์สำหรับผู้ที่ต้องการเริ่มต้นการเขียน vue ด้วย typescript นะครับ ผู้อ่านท่านไหนสนใจ สามารถอ่านเรื่อง typescript เพิ่มเติมได้ที่ TypeScript: Basic Types
ติดตามอ่านบทความดี ๆ ที่น่าสนใจ ไม่ว่าจะเป็น Machine Learning, Startup, Design, Software Development และ Management ทาง Senna Labs Blog ได้ทุกวัน


Subscribe to follow product news, latest in technology, solutions, and updates
บทความอื่นๆ



Let’s build digital products that are simply awesome !
We will get back to you within 24 hours!ติดต่อเรา








