问题描述
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
)的 removeParent
和 Node
,因为这些函数在调用代码时也用作类型保护。有没有办法告诉 TS 我知道我返回的对象是与参数不兼容的类型?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)