How I do Vue in 2019: TypeScript and TSX

The App.tsx will connect to the Vuex store and pass props to the Adder.tsx, which is the presentation component that will handle the layout and UI.In a large app, you would probably have an AdderContainer.tsx, but for simplicity I am just using App.tsx to interface with the store..Adder.tsx receives data from the store via props, and communicates with the parent by emitting events..This will let us demonstrate:typesafe props, including complex types like Enums and Objectstypechecked events between the parent/child componenthow to get type inference and type safety with Vuex State in componentsStart off by converting App.vue to App.tsx..Update it to contain the following:Since we haven’t created Adder.tsx yet, create it: components/Adder.tsx..Inside components/Adder.tsx, add the following bare-bones component:Now import it in App.tsx: import { Adder } from './components/Adder'..Lastly, head to main.ts and change import App from './App.vue to import { App } from './App'..Run yarn serve (or npm run serve)..localhost:8080 should show the following:Typesafe PropsThe first thing we will demonstrate is typesafe props, including both primitives (like Number and Boolean) as well as complex types, like Enum..In Adder.tsx, add the following:One caveat is you need to type true as true to get TypeScript to check the props at compile time..It is discussed breifly here..One you add that, if your editor supports TypeScript (for example VS Code), head back to App.tsx, and you should see an error, and <Adder > has a red line under it..Towards the end of the error message, it says Type '{}' is missing the following properties from type '{ left: number; right: number; }': left, right.. More details

Leave a Reply