[英]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
I'm not gonna lie, the union type makes me very unhappy.我不会撒谎,工会类型让我很不开心。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.