【问题标题】:Argument of type '(Node & ParentNode) | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element''(Node & ParentNode) | 类型的参数null' 不可分配给“元素”类型的参数。类型“null”不可分配给类型“元素”
【发布时间】:2021-02-20 04:25:35
【问题描述】:

我尝试将节点的parentNode 传递给我的getStyleComputedProperty 函数。

但出现错误:

类型参数'(Node & ParentNode) | null' 不可分配给“元素”类型的参数。类型“null”不能分配给类型“元素”。

代码在这里:

type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];
type Property = NonFunctionPropertyNames<CSSStyleDeclaration>;
export const getStyleComputedProperty = (ele: Element, property: Property): string => {
  const css = window.getComputedStyle(ele, null);
  return css[property];
};

const div = document.createElement('div')
getStyleComputedProperty(div.parentNode, 'position') // tsc throw error

我知道我可以使用像 div.parentNode as Element 这样的类型转换来通过 TSC 类型检查。但我想知道如何在没有类型转换的情况下使类型正确。

这里是TypeScript Playground

【问题讨论】:

    标签: typescript dom typescript-typings


    【解决方案1】:

    尝试使用parentElement 而不是parentNode

    type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];
    type Property = NonFunctionPropertyNames<CSSStyleDeclaration>;
    export const getStyleComputedProperty = (ele: Element, property: Property): string => {
      const css = window.getComputedStyle(ele, null);
      return css[property];
    };
    
    const div = document.createElement('div')
    if (div.parentElement) {
      getStyleComputedProperty(div.parentElement, 'position')
    }
    
    

    Here你可以找到这两者的区别

    你是对的,使用类型转换 as 应该是最后的手段

    【讨论】:

    • parentNode 和 parentElement 的行为好像不太一样。所以我担心它会在运行时中断。
    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2023-01-20
    • 2021-08-15
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多