gpt4 book ai didi

typescript - 捕获数组的类型,以便我们可以将其映射到联合类型的数组中

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:10 25 4
gpt4 key购买 nike

class Custom1 { }

class Custom2 { }

class Custom3 { }

class Custom4 { }

class Foo {
custom1s: Custom1[];
custom2s: Custom2[];
custom3: Custom3;
custom4: Custom4;
}

type SomeMapping<T> = {
[P in keyof T]
: T[P] extends any[] ? object[]
: (T[P] | object);
}

type FooMapped = SomeMapping<Foo>;

实际的输入是这样的:

type FooMapped = { 
custom1s: object[];
custom2s: object[];
custom3: object | Custom3;
custom4: object | Custom4;
}

我想要的是:

type FooMapped = { 
custom1s: (object | Custom1)[];
custom2s: (object | Custom2)[];
custom3: object | Custom3;
custom4: object | Custom4;
}

我们如何捕获数组的类型以便将其转换为联合?

最佳答案

有类型

type FooMapped = { 
custom1s: Custom1[];
custom2s: Custom2[];
custom3: object | Custom3;
custom4: object | Custom4;
}

你应该这样做

type SomeMapping<T> = {
[P in keyof T]
: T[P] extends (infer U)[] ? U[]
: (T[P] | object);
}

并实现这种类型

type FooMapped = { 
custom1s: (object | Custom1)[];
custom2s: (object | Custom2)[];
custom3: object | Custom3;
custom4: object | Custom4;
}

这样做

type SomeMapping<T> = {
[P in keyof T]
: T[P] extends (infer U)[] ? (U | object)[]
: (T[P] | object);
}

引用:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html (“条件类型”部分)

关于typescript - 捕获数组的类型,以便我们可以将其映射到联合类型的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com