typescript - 打字稿函数返回没有 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?
解决方案
条件类型(其中NonNullable
is)通常不会在泛型函数中提供良好的实现。您可以使用类型断言来使其工作(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
推荐阅读
- .net - .NET CF 2013 与 SQL 问题
- elasticsearch - ElasticSearch 简单匹配
- spring-boot - Spring Stream - 将事件发送到多个目的地
- laravel - 将图像转换为 base 64 而不存储在任何文件夹中
- ios - 如何在屏幕锁定/背景模式下播放音频
- angular - 扩展 HttpErrorResponse 导致错误找不到模块'@angular/common/http'
- python - 找不到 pip.exe 文件
- java - 如何将 jaxb.properties 放置在 Spring Boot 项目的 META-INF 或资源文件夹中?
- javascript - 每次单击后更改 ractive 按钮的单击
- android - Android Studio:com.android.volley.TimeoutError。发生什么事?