【发布时间】:2020-09-01 20:58:16
【问题描述】:
我正在使用 TypeScript 和 React。 我有一个简单的函数,应该将脚本属性从一个复制到另一个:
type MutableScriptProperties = Pick<
HTMLScriptElement,
'async' | 'crossOrigin' | 'defer' | 'integrity' | 'noModule' | 'referrerPolicy' | 'type' | 'nonce'
>;
type Values<T extends object> = T[keyof T];
type MutableScriptKey = keyof MutableScriptProperties;
type MutableScriptValue = Values<MutableScriptProperties>;
const scriptPropertiesToClone: MutableScriptKey[] = [
'async',
'crossOrigin',
'defer',
'integrity',
'noModule',
'nonce',
'referrerPolicy',
'type',
];
function cloneScriptProperties(source: HTMLScriptElement, target: HTMLScriptElement): HTMLScriptElement {
scriptPropertiesToClone.forEach((propKey) => {
const sourceValue = source[propKey] as MutableScriptValue;
if (sourceValue !== undefined) {
target[propKey] = sourceValue; // this line throws an error
}
});
return target;
}
在标有注释的行中,我收到以下错误:
Type 'string | boolean | null' is not assignable to type 'never'.
Type 'null' is not assignable to type 'never'.ts(2322)
这些 HTMLScriptTag 道具中的任何一个会返回或标记为never 有什么原因吗?
什么是不涉及强制转换的正确解决方案?
【问题讨论】:
标签: javascript html reactjs typescript dom