打字稿:如何合并此交集的表示(在工具提示中)? [英] Typescript: how to merge the representation (in tooltip) of this intersection?

查看:18
本文介绍了打字稿:如何合并此交集的表示(在工具提示中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重载的函数:

interface FunctionWithOverload {
    (): {
        a: 1
        b: 1
    }

    <T>(arg: T): {
        a: 1
        b: 1
    } & (T extends number ? { c: 1 } : {})
}

const fwo: FunctionWithOverload = () => {return {} as any}

const result = fwo() // result has a nice type: {a: 1, b: 1}
const result1 = fwo(1) // result1 does not: {a: 1, b: 1} & {c: 1}

游乐场

如果您将鼠标悬停在 result 上,您可以在工具提示中看到它有一个很好的类型 {a:1,b:1},但是 result1 有一个丑陋的类型 {a:1, b:1} &{c:1}.

If you hover over result, you can see it has a nice type {a:1,b:1} in the tooltip, however result1 has an ugly type {a:1, b:1} & {c:1}.

问题是:我如何以某种方式合并 {a:1, b:1} &{c:1}{a:1, b:1, c:1} 在我的情况下?

The question is: how do I somehow merge {a:1, b:1} & {c:1} to {a:1, b:1, c:1} in my case?

函数重载必须保持原样,即不允许在返回类型中添加相互可选的属性 c.

The function overloads must be as they are, i.e. I am not allowed to add a mutual optional property c to the return type.

不应将任何类型别名添加到工具提示的输出中(除非它是此问题的唯一解决方案).

Any type alias names shouldn't be added to the output in the tooltip (unless it's the only solution to this problem).

美观很重要,因为它符合我的任务要求.

The prettiness matters because it's in the requirements of my task.

推荐答案

我已经设法(在 TitianCernicova-Dragomir 的帮助下)解决了这个问题!像这样:

I've managed (with the help of TitianCernicova-Dragomir) to solve this! Like this:

interface FunctionWithOverload {
    (): {
        a: 1
        b: 1
    }

    <T>(arg: T): Id<{
        a: 1
        b: 1
    } & (T extends number ? { c: 1 } : {})>
}

type Id<T>={} & { [P in keyof T] :T[P]}

const fwo: FunctionWithOverload = () => {return {} as any}

const result = fwo() // result has a nice type: {a: 1, b: 1}
const result1 = fwo(1) // result1 DOES HAVE TOO!!! {a: 1, b: 1, c: 1} 

游乐场

我认为它的工作方式可能是:TS 引擎认为映射类型值得命名类型,如接口,而任何联合、交集(如上面的解决方案)或基本类型就像字符串文字不是.

I think the way it works probably is: the TS engine considers mapped types as worthy of being named types, like interfaces, while any unions, intersections (like in the solution above) or basic types like string literals are not.

这篇关于打字稿:如何合并此交集的表示(在工具提示中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆