Home > other >  Best practices for declaring or assigning types
Best practices for declaring or assigning types

Time:06-23

I'm a beginner with TypeScript (Day 1), but have worked on above average JavaScript projects. I'm looking for advice about some "best practices" and standards when it comes to declaring or assigning types in code. At the moment, I find myself doing it for literally everything which is essentially making my code unreadable.

For example, consider this:

import {createApp, DefineComponent} from 'vue'
import {createRouter, createWebHistory, Router, RouteRecordRaw, RouterHistory} from 'vue-router'
import NPage from '~/layouts/N-Page.vue'
const router : Router = createRouter({
  history: <RouterHistory>createWebHistory(),
  routes: <RouteRecordRaw[]>[{
    component: <DefineComponent>NPage,
    name: <string>'home',
    path: <string>'/',
  }]
})
createApp(NPage).use(router).mount('#app')

This is a simple main.ts setup for Vue.js. Now, my IDE (IntelliJ IDEA), was able to determine the type for router by itself. However, I went ahead and declared the type explicitly. Same with history, routes, etc. What's worse, I find myself declaring type for each individual property too (component, name, path).

This is getting really messy, really fast. And by the looks of it, I can assume, this is not how it's done. In this case, could someone point out, how exactly to make decisions about what we need to declare/assign types for and what not?

CodePudding user response:

That's not a good idea.

You typically don't use explicit types when the type is trivially inferred. All those functions return a type that Typescript already knows about and it's completely safe to rely on those.


In fact, your example code should be 100% identical to the plain JS equivalent:

import {createApp, DefineComponent} from 'vue'
import {createRouter, createWebHistory, Router, RouteRecordRaw, RouterHistory} from 'vue-router'
import NPage from '~/layouts/N-Page.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [{
    component: NPage,
    name: 'home',
    path: '/',
  }]
})

Since you are already importing strongly typed code in this file, and your are not exporting any of your own data structures, nothing else should be required here.


More specific advice than that will drift into opinion, but I think when starting out leave types off by default and fix things when you see type errors or you hover over a token in your editor and see the type any. any is bad, don't let values be any.

If you have more specific questions about how to handle specific type annotations feel free to make a new question for the those specific cases.

  • Related