【发布时间】: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 dom typescript-typings