【问题标题】:Why can't some of the properties on the HTMLScriptElement be assigned to in TypeScript?为什么不能在 TypeScript 中分配 HTMLScriptElement 上的某些属性?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2021-07-06
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多