javascript - 为什么不能在 TypeScript 中分配 HTMLScriptElement 上的某些属性?
问题描述
我正在使用 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
?什么是不涉及铸造的正确解决方案?
解决方案
由于某种原因target[propKey]
被推断为never
. 我没有实际的解决方案,而是解决方法(涉及铸造)
(target[propKey] as unknown as MutableScriptValue) = sourceValue
推荐阅读
- node.js - 错误:使用 Google Drive API 创建权限时需要权限类型字段
- html - 如何使占位符字体(形式)大小在设备之间相同?
- rust - 如何在测试范围的mod中使用注解和微?
- hazelcast - hazelcast 开源成本?
- iptables - `iiptables input policy drop`变成`all forward drop`
- node.js - 如何保护 nodejs 中的套接字连接?
- javascript - 如何向动态目标、远程未启用 cors 的 url 发出 fetch 请求?在 http-proxy-middleware 中,可以在目标中使用变量吗?
- logging - 有没有办法从 DAW 中的白菜插件中记录 printk 的某处?
- scala - twitter4s:如何在播放框架中从 Action.async 返回未来
- multithreading - 将 Monix `Task` 转换为 Cats `IO` 后丢失了什么?