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

问题描述 投票:3回答:1

什么是定义可能未定义接口的最佳方式?我所拥有的是这样的。我正在寻找一种替代。一些更优雅,简洁如果可能的话。

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

这是如何我使用它:

const returnObj: TypeOrUndefined<RouteInterface> = 
  redirectChoices.find(
    (option: RouteInterface) => option.test
  );
reactjs typescript
1个回答
3
投票

通常情况下和我个人不喜欢这样写道:

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

另外这个特殊的代码可以写就像这样:

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

returnObj仍然RouteInterface | undefined因为Array.prototype.find返回一个联盟与包括undefined

© www.soinside.com 2019 - 2024. All rights reserved.