Is it possible to form a union type using an interface?

My goal is to call the function getSvgPresentationAttribute using any valid CSS property name as cssStyleAttribute. However, I am encountering an issue with my current code where I receive the error message

Type 'CSSStyleDeclaration' cannot be used as an index type.
.

export function getSvgPresentationAttribute(
    element: SVGElement,
    cssStyleAttribute: CSSStyleDeclaration,
    svgElementAttribute: string
  ): string | undefined {
    const cssStyleValue = element.style[cssStyleAttribute];
    if (cssStyleValue !== "") {
      return cssStyleValue;
    }

    return getSvgAttribute(element, svgElementAttribute);
  }

I'm seeking guidance on how to resolve this issue. Below is the interface I am currently working with.

interface CSSStyleDeclaration {
    alignContent: string;
    alignItems: string;
    alignSelf: string;
    alignmentBaseline: string;
    ...
}

To make the code functional, I believe I may need a different type or solution. Here's what I have in mind:

type CSSStyleDeclaration =
    "alignContent" |
    "alignItems" |
    "alignSelf" |
    "alignmentBaseline";
    ...
}

I welcome any suggestions or solutions to address this challenge.

Answer №1

To indicate to TypeScript that the parameter can be any key of the CSSStyleDeclaration, utilize the keyof operator.

function fetchSvgAttribute(
    svgElement: SVGElement,
    styleAttr: keyof CSSStyleDeclaration,
    attribute: string
  ): string | undefined {
    const styleValue = svgElement.style[styleAttr];
    if (styleValue !== "") {
      return styleValue;
    }

    return getSvgAttribute(svgElement, attribute);
  }

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

The different types of property 'cacheLocation' do not match

I have been working on updating an old React app from JavaScript to Typescript gradually. I started by migrating the configuration file, but encountered an error when renaming it to .TS. Here is the error message: /Users/xx/yy/lulo/src/adalConfig.ts (13, ...

Generate a unique border using jQuery randomization techniques

I've been experimenting with creating a random number and having the border-radius of my div change on every pageload: <script> $(".card-body").each(function(){ var rand = Math.floor(Math.random() * 100) + 1; $(this).css( { borderRadius: rand ...

Disseminate several outcomes using a Discord bot

My first experience using stackoverflow was to seek help regarding a bot created to post results whenever a new episode of a show in the search list is added on nyaa.si. The issue I'm facing is that the bot posts the same episode multiple times within ...

Class-validator: eliminate a field during validation depending on the value of another field

When using class-validator in conjunction with NestJS, I have successfully implemented the following: export class MatchDeclineReason { @IsString() @IsEnum(MatchDeclineReasonType) @ApiProperty() type: MatchDeclineReasonType; @ValidateIf(reason = ...

Is there a way to prevent Intellij from constantly compiling TypeScript at a very slow pace?

In the process of transitioning my Angular 1.x project from vanilla JS to TypeScript, I'm encountering frustratingly slow response times from my IDE.https://i.sstatic.net/LkiDj.png When I uncheck "Track changes" in Settings > Languages & Framework ...

When using Firefox to scale down a div with CSS `moz-transform`, the border details are unfortunately not retained

When viewing the following HTML in Firefox, you may notice that the right and bottom border is missing. However, Chrome and Internet Explorer display it correctly. Is this a bug in Firefox, or is there another method I can use to make it look consistent ...

Combining Content on a GitHub Page

Within the <head> section of my index.html, I have successfully utilized these links on localhost: <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> <link href=&apos ...

Tips for setting up the information in a Bootstrap popover

I am currently working on a Google web app that involves Google Sheets data. My objective is to have the data displayed when hovering over a button, but instead, the data appears directly on the button without the hover display. What might I have done in ...

Is there a way to change the CSS of a sibling element when hovering over it

Imagine a scenario where hovering over one row changes its color. However, what if we want all rows of the same color to highlight when any row is hovered over? Is it possible to achieve this using just CSS? .red-row:hover { background-color: red; } ...

It seems like the recent upgrade to yarn 2 has caused issues with typescript types, whereas the installation of the same project with yarn 1 was

Recently, I've been attempting to update a typescript monorepo to utilize yarn 2, but I've encountered an issue where typescript is struggling to recognize certain react props. This functionality was working fine in yarn 1.x, leading me to believ ...

Is your floating action button malfunctioning?

Having an issue where clicking on a button should bring it to the top and float. The button is coming to the top but not floating. Any suggestions on how to solve this problem? Here is the code: <div class="create-course-info" id="scroll"> <a hr ...

The parameter must be of type 'string', but you are attempting to assign a 'Promise<any>'

Starting a React App requires fetching the user's information from localStorage and initiating a socket connection with the server based on the user's id. However, when trying to pass the user's id to the socket function, TypeScript throws ...

Changing the background color of a fixed header in AngularJS based on the current page

I designed my homepage with a full-height div featuring a video. The header is fixed in position and has a transparent background with white text when positioned over the video. As I scroll down, I dynamically adjust the background to white with black text ...

Another option for document.execCommand('selectAll',false,null)

I've come across a piece of code that allows me to select the text in a div whenever a user clicks on it: <table> <tr> <td> <div contenteditable onClick="document.execCommand('selectAll',false,null)">I& ...

Failed to execute start script 'ng serve' in npm start

Let me make it clear: I'm brand new to AngularJS and pretty much any Web Technology. I consider myself a novice in the realm of Web Development. I attempted to install AngularJS, and truth be told, after numerous "Mysterious Button Clicks", I might ...

Display an element that has been tucked away, and then bring it to life

Is there a way to implement an animation that causes the hidden form to slide from right to left after the .button class is hidden? I have been able to achieve similar effects individually, but struggle with synchronizing their animations. When the butt ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

Styling with CSS for an associative array with multiple columns

How can I modify this PHP function to display its output within a scrolling text box with word wrap in CSS? <?php function prettyPrint( $my_array ) { if (is_array($my_array)) { echo "<table style=border=0 cellspacing=2 cellpadding ...

Creating a relationship of dependence between functions in TypeScript: A guide

Apologies for the unclear title, I'm struggling to articulate my question effectively. Currently, I am attempting to create a method that can parse an object from an XML file. The XML structure (translated to JavaScript using xml-js) appears as follow ...

Is there a way to incorporate background images into the <option> tags within a <select> dropdown menu?

Not sure if browsers support this feature. It works fine in a div, but that's not very semantically correct. Here is a rough mockup of what I'm trying to achieve: Mockup Link /* CSS for select elements on page */ select { position: relative ...