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 ได้ทุกวัน
![Senna Labs](/_next/image?url=%2Fsenalabs.jpg&w=3840&q=75)
![](/_next/image?url=%2Fimages%2Fsubscribe.webp&w=3840&q=75)
Subscribe to follow product news, latest in technology, solutions, and updates
Other articles for you
Let’s build digital products that are simply awesome !
We will get back to you within 24 hours!Go to contact us![](/_next/image?url=%2Fimages%2Ftell-us-arrow.webp&w=384&q=75)
![Contact ball](/_next/image?url=%2Fimages%2Fcontact-ball.webp&w=3840&q=75)
![Contact us bg 2](/_next/image?url=%2Fimages%2Fcontact-us-bg-2.webp&w=3840&q=75)
![Contact us bg 4](/_next/image?url=%2Fimages%2Fcontact-us-bg-4.webp&w=3840&q=75)
![Contact us bg 1](/_next/image?url=%2Fimages%2Fcontact-us-bg-1.webp&w=3840&q=75)
![Ball left](/_next/image?url=%2Fimages%2Fball-left.png&w=1080&q=75)
![Ball right](/_next/image?url=%2Fimages%2Fball-right.png&w=1920&q=75)
![Ball left](/_next/image?url=%2Fimages%2Fball-left.png&w=256&q=75)
![Ball right](/_next/image?url=%2Fimages%2Fball-right.png&w=384&q=75)
![Sennalabs gray logo](/_next/image?url=%2Fimages%2Fsennalabs-gray-logo.webp&w=256&q=75)