【发布时间】:2020-07-31 18:27:35
【问题描述】:
我正在构建一个 TypeScript 库,它利用了另一个库中的一些接口。我正在尝试从泛型类型和我无法控制的接口的交集中定义一个类型,并结合void 之间的联合,这在依赖库中具有特殊含义。
我试图创建一个我所面临问题的最小表示。
export type AllProps<Props> = (Props & IDependecyProps) | void;
interface MyProps {
disableCache: boolean;
}
function doTheThing(props: AllProps<MyProps>) {
// Property 'disableCache' does not exist on type 'AllProps'.
// Property 'disableCache' does not exist on type 'void'.ts(2339)
console.log(props.disableCache);
}
我的目标是AllProps 应该允许您指定disableCache 和IDependecyProps 中的任何属性,或者类型结果为void。我所依赖的库对于void 类型有特殊的意义,这让它很有用。
编辑:我的代码示例太简单了,忘记添加泛型类型。
【问题讨论】:
-
void 中怎么会有类型结果?
-
问题不是很清楚,但简单的
if会细化类型并排除void。 Try -
@AlekseyL.,这正是我们所需要的。简单的
if(props)语句允许 TypeScript 排除void并假设我的类型交集。它完美地工作:)
标签: typescript typescript-typings typescript-generics