angular - 有什么特别的吗?类型 'Node' 无法转换为类型 'ChildNode'

标签 angular typescript dom webpack

我有这个:

const node = window.getSelection().getRangeAt(0).startContainer;
(node as ChildNode).replaceWith(...nodes)

以上在构建时抛出错误:

Type 'Node' cannot be converted to type 'ChildNode'

Property 'remove' is missing in type 'Node'

但是如果我:

(node as any).replaceWith(...nodes)

编译得很好。谁能解释一下吗?

编辑:

ritaj 的回答得到了支持没有解决我的问题

最佳答案

制作类型保护:

function isChildNode(node: Node): node is ChildNode {
    // Might want some other property checks as well
    return 'replaceWith' in node;
}

并保护类型:

const node: Node = window.getSelection().getRangeAt(0).startContainer;

if (isChildNode(node)) {
    node.replaceWith();
}

关于angular - 有什么特别的吗?类型 'Node' 无法转换为类型 'ChildNode',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807577/

相关文章:

javascript - 如何解决 Ionic Uncaught Error : Cannot find module "." when adding new page?

angular - 在 Jasmine 中对 MatDialog 进行单元测试时无法读取未定义的属性 'afterClosed'

Angular 9.0.4,子模块中找不到异步管道(git repo)

typescript - ES6 类实现 Typescript 接口(interface)成为 WET

javascript - 类(Class)后代扰乱事件

javascript - 文本附加和循环效果

javascript - 在 Angular2 路由器导出中加载外部 URL

javascript - Typescript 和 Angular : Type a string to a component class

typescript - es6 和 es2017 之间 tsconfig.json 中的 'lib' 属性的区别?

javascript - Firefox 无法正确处理 window.onerror 中的 try/catch block