Home > Blockchain >  Using Vue.js img element in Typescript Array
Using Vue.js img element in Typescript Array

Time:01-23

I'm using Vue 2 and Typescript and I've declared a type in my types.ts file:

export type SetupSliderType = {
  name: SetupSliderEnum;
  image: HTMLImageElement;
  title: keyof I18nMessages;
  component: Function;
}

This gives me no errors.

In my RegisterSetup.tsx file I've declared an Array of that type:

private slides: Array<SetupSliderType> = [
    {
      name: SetupSliderEnum.solutions,
      image: <img src={solutions_logo}/>,
      title: I18nMessages['account.register.side.subheading'],
      component: this.renderSlideSolutions
    },
]

The 'image' line in my Array block gives me this error:

Type 'VNode' is missing the following properties from type 'HTMLImageElement': align, alt, border, complete, and 309 more.ts(2740)

types.ts(13, 3): The expected type comes from property 'image' which is declared here on type 'SetupSliderType'

What is the right way to use the <img> element for this syntax or what am I doing wrong?

CodePudding user response:

When you use JSX/TSX to create an element, you're not creating a DOM element, you're creating an object that will be used by Vue.js (or React or similar) later to create or update a DOM element. As the error message is telling you, the type of object in your case is VNode, so you'd use VNode instead of HTMLInputElement in your type:

export type SetupSliderType = {
    name: SetupSliderEnum;
    image: VNode; // <================
    title: keyof I18nMessages;
    component: Function;
}

If you actually wanted to create an HTMLInputElement, you could do that via document.createElement, but it would be very unusual when using a library like Vue.js or React or similar.

  • Related