简体   繁体   English

函数参数类型推断和条件类型

[英]Function argument type inference and conditional type

I'm trying to cover following case:我试图涵盖以下案例:

I have a function which accepts a boolean and returns value of RealItem | ImaginaryItem我有一个函数,它接受一个布尔值并返回RealItem | ImaginaryItem RealItem | ImaginaryItem type. RealItem | ImaginaryItem类型。 I'm using conditional type to narrow the return type based on boolean argument.我使用条件类型来缩小基于boolean参数的返回类型。

type RealItem = { color: string }
type ImaginaryItem = { description: string }

export function createItem<T extends boolean>(isReal: T): T extends true ? RealItem : ImaginaryItem

export function createItem<T extends boolean>(isReal: T): RealItem | ImaginaryItem {
  return isReal ? { color: 'red' } : { description: 'Crazy thing' }
}

My signatures seem to be working fine for following cases:我的签名似乎适用于以下情况:

const a = createItem(true)      | typeof a -> RealItem
const b = createItem(false)     | typeof b -> ImaginaryItem


let isReal = true
const a = createItem(isReal)    | typeof a -> RealItem

let isReal = false
const b = createItem(isReal)    | typeof b -> ImaginaryItem

However if I wrap createItem into another function and pass isReal argument:但是,如果我将createItem包装到另一个函数中并传递isReal参数:

const itemsFactory = (isReal: boolean) => createItem(isReal)

TS seems to fail to deduct return type narrowed with conditional return type: TS 似乎无法扣除条件返回类型缩小的返回类型:

const a = itemsFactory(true)    | typeof a -> RealItem | ImaginaryItem
const b = itemsFactory(false)   | typeof b -> RealItem | ImaginaryItem

TS playground TS游乐场

I'm not gonna lie, the union type makes me very unhappy.我不会撒谎,工会类型让我很不开心。

  • Is this some sort of limitation of TS capabilities in type interference?这是类型干扰中 TS 能力的某种限制吗?
  • Can I help TS understand how to interpret higher function arguments?我可以帮助 TS 了解如何解释更高的函数参数吗?

I know I could use type guards here, however they don't go well with my current code structure.我知道我可以在这里使用类型保护,但是它们不适合我当前的代码结构。

The type information of isReal is essentially lost with the itemsFactory function since you specified isReal as a boolean here.由于您在此处将isReal指定为boolean ,因此itemsFactory函数基本上丢失了isReal的类型信息。

To fix this, you can also add the same generic type to the itemsFactory function:要解决此问题,您还可以将相同的泛型类型添加到itemsFactory函数:

const itemsFactory = <T extends boolean>(isReal: T) => createItem(isReal)

Playground 操场

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

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