TypeScript - 按函数断言的窄类型

问题描述

我试图让 TS 缩小我在函数中手动修改的类型:


interface Node {
  parent: string | null;
}

interface noparent extends Node {
  parent: null;
}

interface HasParent extends Node {
  parent: string;
}

// Node -> HasParent
// ok,Node Now kNown to have parent
export const setParent = (n: Node): asserts n is HasParent => {
  n.parent = 'parent added';
};

// Node -> noparent
// ok,Node Now kNown to have no parent
export const unsetParent = (n: Node): asserts n is noparent => {
  n.parent = null;
};

// noparent -> HasParent
// error: A type predicate's type must be assignable to its parameter's type.
export const addParent = (n: noparent): asserts n is HasParent => {
  // ... use n as noparent ...

  (n as Node).parent = 'parent';
};

// HasParent -> noparent
// error: A type predicate's type must be assignable to its parameter's type.
export const removeParent = (n: HasParent): asserts n is noparent => {
  // ... use n as HasParent ...

  (n as Node).parent = null;
};

我需要编写具有特定类型(不是 addParent)的 removeParentNode,因为这些函数调用代码时也用作类型保护。有没有办法告诉 TS 我知道我返回的对象是与参数不兼容的类型?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...