Top tips for defining or assigning data types

As a newcomer to TypeScript on my first day, I have experience working on JavaScript projects above the average level. I am seeking advice on best practices and standards for declaring or assigning types in code. Currently, I tend to specify types for everything, which ends up making my code hard to read.

For instance, take a look at 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 represents a basic main.ts setup for Vue.js. Despite my IDE (IntelliJ IDEA) automatically inferring the type for router, I still explicitly declared it. The same goes for history, routes, and so on. To make matters worse, I often find myself specifying types for each individual property (component, name, path).

This approach is leading to a messy codebase quickly. It seems apparent that this may not be the correct way to go about it. In light of this, could someone guide me on how to determine when we should declare/assign types and when we shouldn't?

Answer №1

It may not be the best decision.

Usually, explicit types are unnecessary when TypeScript can easily infer them. The functions you are using already have well-defined types that TypeScript recognizes, so it is safe to rely on them without explicitly specifying types.


In reality, your code example should be exactly the same as its plain JavaScript 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 importing strongly typed code in this file and not creating any custom data structures, there is no need for additional type annotations here.


As a general rule of thumb, I suggest omitting types initially and addressing type errors as they arise or when you encounter the any type while hovering over a token in your editor. It's important to avoid using any whenever possible.

If you have more specific questions regarding how to handle particular type annotations, feel free to ask a separate question tailored to those specific cases.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...

"Encountered a 'Module not found: Error: Can't resolve' issue while attempting to install from GitHub. However, the standard installation process

I am currently utilizing the Quilljs JavaScript library for a project in Angular. After installing it with the following command: npm install --save quill Everything appears to be functioning correctly, and I am able to import the Quill class into my Ty ...

Exploring ways to showcase validation errors in Laravel blade using Vue.js

I have a Laravel view that includes a form, and I'm trying to utilize Axios for form submission. If there are any errors returned in the response after submitting the form, they should be displayed in the appropriate fields. I've encountered tw ...

Avoiding the default action and using a false return value do not produce the

Despite trying preventDefault, return false, and stopImmediatePropagation, the page continues to redirect back to the first selection instead of redirecting to the textarea after inputting all required fields and clicking on the button. The issue persists ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

Different types of outputs that are suitable for a callback

I am currently developing a small node.js project focused on retrieving search terms from a Twitter feed. Although the search functionality is in place, I am facing difficulties in displaying this data on my webpage. The information I wish to showcase is s ...

Pair a specific portion of text with another string

I'm having trouble finding a substring within a string. The substring and the string are as follows: var str="My name is foo.I have bag(s)" var substr="I have bag(s)" When I use str.match(substr), it returns null, probably because the match() funct ...

What is the best way to update objects in different scopes within AngularJS?

Exploring AngularJS for the first time, I find myself struggling with understanding scopes. My current dilemma involves modifying an object or variable from multiple scopes. Here's the scenario: I'm looking to centralize the user notification Co ...

What is the best way to iterate through files within a directory and its nested subdirectories using electron?

I am currently working on developing a desktop application that involves scanning through a directory, including all subdirectories, to locate files containing specific characters in their filenames. Is it feasible to accomplish this task using Electron? ...

Combining and sorting cursor data from multiple collections based on date

Can you combine two or more different collections and arrange them by createdAt? For example, suppose we have data like this: CollectionA.insert({ createdAt: new Date(), field1: value1, field2: value3, field3: value2, ...

Converting a Javascript string to 'Title Case' does not yield any results

I'm having trouble identifying the bug in this code as it's not generating any output: function convertToTitleCase (inputString) { var wordArray = inputString.split(' '); var outputArray = []; for (var j = 0; j ...

What is the best way to adjust and filter an array based on a single value?

Here is an array that needs to be modified: [ {name: "test", value: "test", group: 0}, {name: "test1", value: "test2", group: 0}, {name: "test3", value: "test3", group: 1}, {name: "te ...

"Implementing a Vue datepicker within Nuxt3: Step-by-step guide

I have been attempting to implement the vue-datepicker plugin from without success. Initially, I created a class in my \plugins directory: ('\plugins\vue-datepicker.js') import Datepicker from '@vuepic/vue-datepicker'; ...

Trigger a Tabulator event when a checkbox is selected in Vue 3

Currently, I am utilizing Vue3 along with Tabulator (5.2.7) to create a data table using the Composition API. In the following code snippets, I have excluded irrelevant parts of the code. //DataTable.vue <script setup> import { TabulatorFull as Tabu ...

Show information in a text field from JSON in SAPUI5

How can I populate a text box with data from JSON using SAPUI5? // Sample JSON data var data = { firstName: "John", lastName: "Doe", birthday: {day:01,month:05,year:1982}, address:[{city:"Heidelberg"}], enabled: true }; // Create a JS ...

Exploring VueJS: Understanding how to access nested child components

Running on version 2.2.2, my VueJS app has a specific structure that I need assistance with. How can I access all the Account components from a method within my Post component? The number of Accounts varies, so I want to be able to grab all loaded Account ...

Executing an AJAX request when the window is closed using jQuery

I have a clear question: how can I trigger an ajax call when the user clicks on the browser close button, but before actually closing the window? Are there any possible solutions for this specific scenario? I do not want any confirmation boxes - just a w ...

Calculating the dot product of two arrays using JavaScript

let array1 = [2,4,6] let array2 = [3,3,3] let result = dotProduct(array1,array2) // should return 36 Can you suggest a streamlined approach to creating the dotProduct function without relying on external libraries? ...

What is the best way to transfer data between functions prior to serializing and submitting the form?

Here are two functions I am working with: $("#form_pdetail").on("click", "#register_button", function() { var detail_add = $("#form_pdetail").serialize(); var request = $.ajax({ type: 'POST', url: "{{ path('product_d ...

Making an Ajax call in ASP.Net MVC5 will only execute once

I'm currently working on an AJAX function in ASP.Net MVC5, and I've encountered a problem where the form AJAX request only works once. The issue arises on a search page - when I select a filter and click "search," I receive the correct results. H ...