Home > Mobile >  Typescript an add function with nullable argument and declaring return type by using condition type
Typescript an add function with nullable argument and declaring return type by using condition type

Time:01-01

I want to write an add function
when arguments are all null, then return null
when one of the arguments is null, then return another one
when arguments are all numbers then return their sum

playground

function add<A extends number | null, B extends number | null>(a: A, b: B): 
  A extends null
    ? B extends null
      ? null
      : B
    : B extends null
      ? A 
      : number {
    if (a == null) {
        if (b == null) { 
            return null // Type 'null' is not assignable to type 'A extends null ? B extends null ? null : B : B extends null ? A : number'.
        } else {
            return b
        }
    } else {
        if (b == null) { 
            return a
        } else {
            return a   b
        }
    }
}

const a = add(1 , 333) // number
const b = add(1 , null) // 1
const c = add(null , 2) // 2
const d = add(null , null) // null

why does the compiler complain like this? the code and return type declaration are almost the same.

CodePudding user response:

How is it like this?

function add<A extends number | null, B extends number | null>(a: A, b: B): number | null {
      if (a == null) {
        if (b == null) {
          return null;
        } else {
          return b as NonNullable<B>;
        }
      } else {
        if (b == null) {
          return a as NonNullable<A>;
        } else {
          return a   b;
        }
      }
    }

CodePudding user response:

I would just use overloads:

function add(a: number, b: number): number;
function add<A extends number>(a: A, b: null): A;
function add<B extends number>(a: null, b: B): B;
function add(a: null, b: null): null;
function add(a: number | null, b: number | null) {
    return a === null && b === null ?  null : (a ?? 0)   (b ?? 0);
}

Note that overloads do not type check the implementation.

Playground

  • Related