简体   繁体   English

TypeScript Generics:用联合定义类型交集

[英]TypeScript Generics: defining type intersection with a union

I'm building a TypeScript library that leverages some interfaces from another library.我正在构建一个 TypeScript 库,它利用了另一个库中的一些接口。 I'm trying to define a type from the intersection of a generic type and an interface I don't control, combined with a union between void , which has special meaning in the dependency library.我试图从泛型类型和我不控制的接口的交集定义一个类型,并结合void之间的联合,这在依赖库中具有特殊含义。

I've tried to create a minimal representation of the issue I'm facing.我试图为我所面临的问题创建一个最小的表示。

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);
}

My goal is that the AllProps should allow you to specify either disableCache , and any properties in IDependecyProps , OR the type results in void .我的目标是AllProps应该允许您指定disableCacheIDependecyProps中的任何属性,或者类型导致void The library I depend on has a special meaning for void type, which makes it useful.我所依赖的库对void类型有特殊的意义,这使得它很有用。

EDIT: I made the code sample too simple, forgot to add the generic type.编辑:我使代码示例太简单了,忘记添加泛型类型。

You can use a type assertion on your props and check for the existence of the property, since your example is boolean we need to check if it is not undefined您可以在道具上使用类型断言并检查属性是否存在,因为您的示例是boolean我们需要检查它是否undefined

Read More Here 在这里阅读更多


interface IDependecyProps {
    something: number
}
export type AllProps = (MyProps & IDependecyProps) | void;

interface MyProps {
  disableCache: boolean;
}

function doTheThing(props: AllProps) {

  if ( typeof((props as MyProps).disableCache)!=='undefined' )
  console.log((props as MyProps).disableCache);
}
doTheThing({ disableCache: false, something:1})

Playground 操场

Simple if will refine the type and exclude the void :简单的if将改进类型并排除void

function doTheThing(props: AllProps) {
  if (props) {
    console.log(props.disableCache); // props is narrowed to MyProps & IDependecyProps
  }
}

Control flow analysis narrows type of props inside if to MyProps & IDependecyProps .控制流分析将内部props if类型缩小到MyProps & IDependecyProps

Also if is needed anyway to prevent error at runtime ( props parameter can be undefined according to its type definition).此外if无论如何都需要在运行时防止错误( props参数可以根据其类型定义undefined )。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM