简体   繁体   English

我可以从接口创建联合类型吗?

[英]Can I create a union type from an interface?

I want to be able to call the function getSvgPresentationAttribute with any valid CSS property name as cssStyleAttribute.我希望能够使用任何有效的 CSS 属性名称作为 cssStyleAttribute 调用函数 getSvgPresentationAttribute。 But I haven't gotten it to work.但我还没有让它工作。

In my current code below I get the message Type 'CSSStyleDeclaration' cannot be used as an index type.在我下面的当前代码中,我收到消息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);
  }

What can I do about this?我该怎么办?

Here is what the interface I am using looks like.这是我使用的界面的样子。

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

Here is what I guess I would need as a type to make this code (or something similar) work.这是我想我需要作为使此代码(或类似的东西)工作的类型。

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

I am open to any solution.我对任何解决方案持开放态度。

Use the keyof operator to tell typescript that the parameter is any key of CSSStyleDeclaration .使用keyof运算符告诉打字稿该参数是CSSStyleDeclaration任何键。

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

    return getSvgAttribute(element, svgElementAttribute);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM