'(Node & ParentNode) 类型的参数 | null' 不可分配给类型为 'Element' 的参数。类型 'null' 不能分配给类型 'Element'

时间:2021-02-20 04:25:35

标签: typescript dom typescript-typings

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

但出现错误:

<块引用>

'(Node & ParentNode) 类型的参数 | null' 不可分配给类型为 'Element' 的参数。类型 'null' 不能分配给类型 'Element'。

代码在这里:

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

1 个答案:

答案 0 :(得分: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 应该是最后的手段