Tips for choosing the correct type of object to use for styling in Vue/Typescript: { }

This is how I implement styling in my Vue TypeScript project.

    private styleTableObject: CSSStyleSheet = {
      width: '100%',
      height: '76%'
    }

I am being forced to use the any type.

    private styleTableObject: any = {
      width: '100%',
      height: '76%'
    }

Error messages:

Type '{ width: string; height: string; }' is not compatible with type 'CSSStyleSheet'.
  Object literals can only specify known properties, and 'width' does not exist in type 'CSSStyleSheet'.

If I use any type suggested by Visual Studio Code, I receive the following error messages:

 Type '{ width: string; height: string; }' is not compatible with type 'StyleSheet'.
  Object literals can only specify known properties, and 'width' does not exist in type 'StyleSheet'.

219:13 Type '{ width: string; height: string; }' is missing required properties such as alignContent, alignItems, alignSelf, alignmentBaseline, and more.

Answer №1

UPDATE 2024: I originally wrote this answer back in 2020 before transitioning away from Vue to another framework. Therefore, the information provided here may no longer be accurate or relevant. Please refer to kyis' answer for more current details.


To address this issue, utilize

Partial<CSSStyleDeclaration>
instead

Partial<T>

This function constructs a type with all properties of T set to optional. It creates a type that consists of all possible subsets of a specified type

Resource: https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt

Your code snippet will resemble the following:

private styleTableObject: Partial<CSSStyleDeclaration> = {
    width: '100%',
    height: '76%'
}

Answer №2

Vue 3 introduces a new type specifically for CSS property objects. Keep in mind that using

Partial<CSSStyleDeclaration>
may lead to type checking errors in your template (especially when Volar is enabled):

import type { CSSProperties } from 'vue'

const styleTableObject: CSSProperties = {
  width: '100%',
  height: '76%'
}

<div :style="styleTableObject" />

Answer №3

That solution appears to be effective:

const newStyle: Partial<CSSStyleDeclaration> = {};
const newArrowStyle: Partial<CSSStyleDeclaration> = {};

const information = ref({
 strokeWidth: 0.108,
 style: newStyle,
 arrowStyle: newArrowStyle,
});

Is there a method to achieve this without using separate variables when initializing const information?

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

Having difficulty deciphering the legend in the Highcharts library for Angular (angular-highcharts)

I have a requirement to display two datasets as dual column charts. (2) [{…}, {…}] 0: historyDate: "2021-02-10T10:00:000Z" documentStatusHistory: CANCELLED: 6 COMPLETED: 52 IN_PROGRESS: 1 OPEN: 1 ...

Exploring FormArray Validation in Angular 6

Managing around 50 controls on my page, especially when it comes to validation, is a bit overwhelming. I find myself repeating the same Validators for each control. I'm considering grouping the validators into two categories: 1. [Validators.required ...

Unable to retrieve React state within the callback function

As I work with the following components: const ParentComponent: React.FC = () => { // Setting newType to some value within the code const [newType, setNewType] = useState<any>(undefined); // Enabling addEdge to true in another part o ...

Mat backspin dialogue spinner

Our current setup involves using a progress spinner for each API call. The spinner is registered at the app module level, but we are facing an issue where the spinner hides behind the dialog popup. In order to solve this problem, we have decided to includ ...

In TypeScript, what specific type or class does a dynamically imported module belong to?

Can someone assist me in determining the type of an imported module in TypeScript? Here is my query: I have a module called module.ts export class RSL1 {}; Next, I import it into my index.ts using the following code: const script = await import('mod ...

Revamp your hues using Vuejs

I'm facing an issue with changing the color of an object retrieved from an API based on its status. I attempted to achieve this as follows: <b-badge :variant="variant">{{ $t(contract.status) }}</b-badge> Here is the script I use ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...

What is the recommended way to include @types/module in a TypeScript project?

Once I've added a module like @types/express using npm, how can I correctly reference it in typescript? I've tried the following methods: /// <reference path="../node_modules/@types/express/index.d.ts" /> but I still get an error sayin ...

Problem encountered when attempting to retrieve information from a web service in Angular 4

I am currently attempting to retrieve data from a web service API. However, all I can see is the data on the console. The web service requires an ID, so I input the ID first and then proceed to obtain the data related to that ID within the web service us ...

Is there another option for addressing this issue - A function that does not declare a type of 'void' or 'any' must have a return value?

When using Observable to retrieve data from Http endpoints, I encountered an error message stating that "A function whose declared type is neither 'void' nor 'any' must return a value." The issue arises when I add a return statement in ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

"Enhanced Laravel application incorporating Vue.js for data manipulation, utilizing Axios for API interactions

Lately, I've been diving into the world of Laravel and Vue.js. However, I've run into a roadblock while working with server-side interactions. After making a post request to the server and getting back a response, I noticed that there is an extra ...

Top recommendations for keeping @vue/cli-plugin-unit-jest up to date

Seeking guidance on the best approach to update the following components. If I modify one, say @vue/cli-plugin-unit-jest, will the others also be updated automatically? @types/jest": "^24.0.19" @vue/cli-service": "~4.5.0", @vue/test-utils": "^1.0.3 ...

Updating Property of a div in Vue.js

I have a Vue file and I am trying to specify an 'action' attribute for my form. <template> <div> <form> </form> </div> </template> export default { created() { var test = document.getElement ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

The JavaScript function is being triggered multiple times by the event listener, even though I explicitly reference the function

Every time I create an angular controller, I add an event listener. However, when I return to the page after leaving it, a new event listener is added because the constructor is called again. Unfortunately, when this event is triggered, it gets invoked mu ...

Getting the id of a single object in a MatTable

I'm currently working on an angular 8 application where I've implemented angular material with MatTableDatasource. My goal is to retrieve the id from the selected object in my list: 0: {id: "e38e3a37-eda5-4010-d656-08d81c0f3353", family ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

The process of running npx create-react-app with a specific name suddenly halts at a particular stage

Throughout my experience, I have never encountered this particular issue with the reliable old create-react-app However, on this occasion, I decided to use npx create-react-app to initiate a new react app. Below is a screenshot depicting the progress o ...

The HTTPS protocol seems to be causing CORS issues, but I can access http://localhost without

In my current project using TypeScript with Express, I encountered an issue with implementing CORS. In the past, I have successfully added CORS to regular Express.js projects without TypeScript and assumed it would work similarly. However, when making a ba ...