Home > Mobile >  TypeScript function param and return type
TypeScript function param and return type

Time:09-21

type TreeNode = {
  value: number;
  left: TreeNode | null;
  right: TreeNode | null;
};

function minNode(node: TreeNode | null): number | null {
  if (node === null) {
    return null;
  }
  return node.value;
}

const node: TreeNode = {
  value: 1,
  left: null,
  right: null,
};
const a = minNode(node)!;

In this function, when I pass TreeNode it returns number, when I pass null it returns null.
How to modify this function so I can get rid of this ! when node is not null?

CodePudding user response:

Use an overload:

function minNode(node:  null): null;
function minNode(node: TreeNode): number;
function minNode(node: TreeNode | null): number | null {
  if (node === null) {
    return null;
  }
  return node.value;
}
  • Related