什么是定义可能未定义接口的最佳方式?我所拥有的是这样的。我正在寻找一种替代。一些更优雅,简洁如果可能的话。
interface RouteInterface {
path: string;
test: boolean;
}
type TypeOrUndefined<T> = T | undefined;
这是如何我使用它:
const returnObj: TypeOrUndefined<RouteInterface> =
redirectChoices.find(
(option: RouteInterface) => option.test
);
通常情况下和我个人不喜欢这样写道:
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
。