Javascript 在Typescript中仅接受字符串密钥对值的泛型对象
如何将此函数转换为TypescriptJavascript 在Typescript中仅接受字符串密钥对值的泛型对象,javascript,html,typescript,Javascript,Html,Typescript,如何将此函数转换为Typescript interface Attribute { src?: string; alt?: string; href?: string; title?: string; target?: string; } function setAttributes(element: HTMLElement, attributes: Attribute){ for (const key in attributes) { element.setA
interface Attribute {
src?: string;
alt?: string;
href?: string;
title?: string;
target?: string;
}
function setAttributes(element: HTMLElement, attributes: Attribute){
for (const key in attributes) {
element.setAttribute(key, attributes[key]); // this part fails
}
}
在这里,attributes[key]
无法工作。我怎样才能解决这个问题
我对功能进行了如下重组:
function setAttributes(element: HTMLElement, attributes: Attribute) {
for (const [key, value] of Object.entries(attributes as Record<string, string>)) {
element.setAttribute(key, value);
}
}
在这种情况下,我通常只使用
keyof
类型断言:
function setAttributes(element: HTMLElement, attributes: Attribute) {
for (const key in attributes) {
const value = attributes[key as keyof Attribute];
// still might error, because value could be undefined
element.setAttribute(key, value);
}
}
在我向
tsconfig
的lib
当前工作段
函数setAttributes(元素:HTMLElement,属性:Attribute){
for(对象条目的常量[键,值](属性作为记录)){
setAttribute(键、值);
}
}
如果未配置正确的libs
,则会发生条目错误。类型定义似乎在lib.es2017.object.d.ts
中,上面的es2017
可能会这样做。如果在属性中有一个不是字符串的属性,这确实会出错,解决方法是在校准setAttribute()之前提供默认值或进行检查
@MikeS.:问题不在于属性不能是string,它们都是可选的,因此类型将是string | undefined
(即使键真的丢失了也不会显示在循环中)。对不起,我的措辞太糟糕了。我的意思是,如果它是string | undefined或任何其他类型/类型联合,那么它就不是string
function setAttributes(element: HTMLElement, attributes: Attribute) {
for (const key in attributes) {
const value = attributes[key as keyof Attribute];
// still might error, because value could be undefined
element.setAttribute(key, value);
}
}
function setAttributes(element: HTMLElement, attributes: Attribute) {
for (const [key, value] of Object.entries(attributes as Record<string, string>)) {
element.setAttribute(key, value);
}
}