简体   繁体   English

没有 null 或 undefined 的 Typescript 函数返回值

[英]Typescript function returning value without null or undefined

I'm trying to write a function which returns a value or if the value is null or undefined it should return a default value.我正在尝试编写一个返回值的函数,或者如果该值为空或未定义,则它应该返回一个默认值。

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

I get the error我收到错误

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

NonNullable should be A without null or undefined and that's what I checked in the if? NonNullable 应该是没有 null 或 undefined 的 A,这就是我在 if?

Here is the code in ts playground. 这是 ts 游乐场中的代码。

Conditional type (of which NonNullable is) usually don't provide a good implementation in generic functions.条件类型(其中NonNullable是)通常不能在泛型函数中提供良好的实现。 You could use a type assertion to get it to work ( return input as any );您可以使用类型断言来使其工作( return input as any );

A safer approach might be to switch up the types a bit:更安全的方法可能是稍微切换类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM