首页 > 解决方案 > 打字稿函数返回没有 null 或 undefined 的值

问题描述

我正在尝试编写一个返回值的函数,或者如果该值为 null 或未定义,它应该返回一个默认值。

function test<A, B>(input: A, fallbackValue: B): NonNullable<A> | B {
 if (input == null || input == undefined) {
   return fallbackValue;
 } else {
   return input;
 }
}

我得到错误

Type 'A' is not assignable to type 'B | NonNullable<A>'.
  Type 'A' is not assignable to type 'NonNullable<A>'.

NonNullable 应该是没有 null 或 undefined 的 A,这就是我在 if?

这是 ts 操场上的代码。

标签: typescript

解决方案


条件类型(其中NonNullableis)通常不会在泛型函数中提供良好的实现。您可以使用类型断言来使其工作(return input as any);

一种更安全的方法可能是稍微切换类型:

function test<A, B>(input: A | undefined | null, fallbackValue: B): A | B {
    if (input == null || input == undefined) {
        return fallbackValue;
    } else {
        return input;
    }
}

declare var s: string | null;
let a = test(s, "") // string

推荐阅读