【问题标题】:TypeScript Generics: defining type intersection with a unionTypeScript 泛型:用联合定义类型交集
【发布时间】: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 应该允许您指定disableCacheIDependecyProps 中的任何属性,或者类型结果为void。我所依赖的库对于void 类型有特殊的意义,这让它很有用。

编辑:我的代码示例太简单了,忘记添加泛型类型。

【问题讨论】:

  • void 中怎么会有类型结果?
  • 问题不是很清楚,但简单的if 会细化类型并排除voidTry
  • @AlekseyL.,这正是我们所需要的。简单的 if(props) 语句允许 TypeScript 排除 void 并假设我的类型交集。它完美地工作:)

标签: typescript typescript-typings typescript-generics


【解决方案1】:

简单的if 将优化类型并排除void

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

控制流分析将props 内部if 的类型缩小到MyProps &amp; IDependecyProps

还需要if 以防止运行时出错(props 参数可以是undefined,根据其类型定义)。

Playground

【讨论】:

    【解决方案2】:

    您可以在您的道具上使用类型断言并检查属性是否存在,因为您的示例是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

    【讨论】:

    • 对不起,我似乎把代码示例过于简化了。如果我始终确切地知道期望什么类型,这将起作用,但实际上那里有一个泛型。我想知道,我能否以某种方式推断泛型类型 Props 是什么,然后按照您的建议使用类型断言?
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2021-10-18
    • 2021-06-05
    • 2020-04-12
    • 2019-12-14
    • 1970-01-01
    • 2017-08-23
    • 2021-03-26
    相关资源
    最近更新 更多