首页 > 解决方案 > 为什么不能在 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?什么是不涉及铸造的正确解决方案?

标签: javascripthtmlreactjstypescriptdom

解决方案


由于某种原因target[propKey]被推断为never. 我没有实际的解决方案,而是解决方法(涉及铸造)

   (target[propKey] as unknown as MutableScriptValue) = sourceValue 

推荐阅读