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;
};
我需要用特定類型(不是 Node)來編寫 addParent 和 removeParent,因為這些函數在調用代碼中也充當類型保護。是否有方法告訴 TypeScript,我知道我返回的對象是一個與參數不兼容的類型?