如何定义可能未定义的类型

时间:2019-02-03 17:20:33

标签: reactjs typescript

定义可能未定义的接口的最佳方法是什么?我有这个。我正在寻找替代方案。如果可能的话,更优雅简洁。

interface RouteInterface {
  path: string;
  test: boolean;
}
type TypeOrUndefined<T> = T | undefined;

这是我的使用方式:

const returnObj: TypeOrUndefined<RouteInterface> = 
  redirectChoices.find(
    (option: RouteInterface) => option.test
  );

1 个答案:

答案 0 :(得分:3)

通常我个人都是这样:

adb shell sendevent /dev/input/event6 3 53 935
adb shell sendevent /dev/input/event6  0 0 0
adb shell sendevent /dev/input/event6 3 54 500
adb shell sendevent /dev/input/event6  0 0 0
adb shell sendevent /dev/input/event6 3 57 1
adb shell sendevent /dev/input/event6  0 0 0
adb shell sendevent /dev/input/event6 3 53 789
adb shell sendevent /dev/input/event6  0 0 0
adb shell sendevent /dev/input/event6 3 54 500
adb shell sendevent /dev/input/event6  0 0 0
adb shell sendevent /dev/input/event6 3 57 0
adb shell sendevent /dev/input/event6  0 0 0

这个特殊的代码也可以这样写:

const returnObj: RouteInterface | undefined = 
  redirectChoices.find(
    (option: RouteInterface) => option.test
  );

const returnObj = redirectChoices.find( (option: RouteInterface) => option.test ); 仍为returnObj,因为RouteInterface | undefined返回了包含Array.prototype.find的并集。