我希望能够使用任何有效CSS属性名称(如cssStyleAttribute)调用函数getSvgPresentationAttribute。但是我还没有开始工作。
在下面的当前代码中,我收到消息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);
}
对此我该怎么办?
这是我正在使用的界面。
interface CSSStyleDeclaration {
alignContent: string;
alignItems: string;
alignSelf: string;
alignmentBaseline: string;
...
}
这是我需要的一种类型,以使此代码(或类似内容)正常工作。
type CSSStyleDeclaration =
"alignContent" |
"alignItems" |
"alignSelf" |
"alignmentBaseline";
...
}
我愿意接受任何解决方案。
答案 0 :(得分:0)
使用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);
}