【发布时间】:2022-01-05 14:03:38
【问题描述】:
我一直在努力让对象参数影响函数的返回类型。
主要问题
这是一个带有 createArray 函数的示例,向您展示我的意思。
interface Selectable { selectable: boolean; }
interface SelectableReturn { selected: {value:any, index:number} }
interface Distant { distant: boolean; }
interface DistantReturn { distances: number[]; }
// All possible type combinations (all objects we can pass to the function)
type Possibilties = Distant | Selectable;
// Here we create the function definitions
declare function createArray(arr: any[], options?: undefined): any[];
declare function createArray(arr: any[], options?: Selectable): any[] & SelectableReturn;
declare function createArray(arr: any[], options?: Distant): any[] & DistantReturn;
declare function createArray(arr: any[], options?: Selectable & Distant): any[] & SelectableReturn & DistantReturn;
在未来,您可以想象为对象添加新选项。你能看出你会花多少时间来实现这个吗? 如果我有 5 个选项,我将必须有 5² = 25 个函数声明...
我想要的是根据选项类型自动将属性附加到返回的数组。
第二个问题
如您所见,此代码有效,但是当您像这样创建数组时:
const arr = createArray([1,2,3], {selectable: true});
你没有得到智能感知,这是因为“可能性”界面...... 有没有办法检测“选项”类型,推断返回类型并维护智能感知?
Here 是一个指向 Typescript 游乐场的链接。
【问题讨论】:
-
this approach 是否满足您的需求?如果是这样,我可以写一个答案;如果没有,请告诉我缺少的内容,最好是 edit 您的示例,以展示不满意的用例。
-
你好@jcalz。谢谢回复。我查看了您的代码并从中学到了一些东西。我不知道 Partial typescript 界面是如何工作的。谢谢。虽然我不太确定这就是我要找的东西。也许我没有为我的问题提供足够的细节。我编辑了我的帖子并添加了一个指向我在操场上创建的代码的链接(我无法在评论部分添加它,因为网址太长了)。
-
嗯,现在您输出的是返回类型的 intersection 而不是 union,并且您还与一些泛型类型相交 @987654328 @ 没有推理站点(当您调用
createArray()时如何指定T)?我可能可以很容易地给出交集而不是联合,但是T事情很奇怪,似乎与你所问的问题无关。我有点希望,如果您对我的实现有疑问,您会指出需要更改的具体内容,而不是扩大问题范围。不知道如何继续。 -
也许我的代码问题与 Intellisense 有关?如果是这样this 可能会更好。如果这对你有用,我会写下来,希望你能保存 intersection-instead-of-union 和 uninferrable-generic-
T以备将来的一些问题。告诉我。 -
我相信我试图让我的代码更清晰,以便人们理解。但是,如果您说第二部分似乎无关紧要,我可能没有这样做(对不起)。我只关注在第一部分作为参数发送的对象。我应该从一开始就指定我的问题。
标签: typescript types typescript-typings