gpt4 book ai didi

typescript - 如何创建原始类型和自定义类型的联合,并更改原始类型的某些属性并保持不变?

转载 作者:行者123 更新时间:2023-12-02 16:23:21 25 4
gpt4 key购买 nike

我正在尝试为一个函数编写类型,该函数应该接受一个对象及其一些键作为参数,并返回一个新对象,其中指定键的值可以是原始对象或原始值类型的集合/数组.

例如:如果我们要传递以下类型的对象:

interface Example {
a: number
b: number
c: string
}

并传递ac作为键,那么返回的类型将为

{
a: number | Set<number> | number[]
b: number
c: string | Set<string> | string[]
}
<小时/>

我设法通过定义以下类型来做到这一点

type SetOrArray<T, K extends (keyof T)[]> = { [V in K[number]]: Set<T[V]> | T[V][] }
type UnionType<T, K extends (keyof T)[]> = T | SetOrArray<T, K>
<小时/>

但是当我对一个对象尝试此操作时,只有传递的键(以 K 为单位)会保留在生成的 UnionType 和其余键中,由于 T |< ,这些键应该与原始类型一起存在/strong> union,在 UnionType 上不存在。

例如:

function afunc<T, K extends (keyof T)[])>(obj: T, ...keys: K): UnionType<T, K> {
return obj // just for example
}

const obj = {a: 1, b: 2, c: "apple"}
const res = afunc(obj, "a", "c")
// res.a exists with type number | Set<number> | number[]
// res.c exists with type string | Set<string> | string[]
// but res.b does not exist, whereas it should have had type number

最佳答案

我刚刚为缺失字段添加了一种附加类型,请尝试以下代码:

interface Example {
a: number
b: number
c: string
}

type SetOrArray<T, K extends (keyof T)[]> = { [V in K[number]]: T[V] | Set<T[V]> | T[V][] }
//Use exclude to create object with missing field
type Outersect<T, K extends (keyof T)[]> = { [P in Exclude<keyof T, keyof SetOrArray<T, K>>]: T[P] }
//And union with SetOrArray type
type UnionType<T, K extends (keyof T)[]> = Outersect<T, K> & SetOrArray<T, K>

function afunc<T, K extends (keyof T)[]>(obj: T, ...keys: K): UnionType<T, K> {
return obj // just for example
}


const obj = { a: 1, b: 2, c: "apple" }
const res = afunc(obj, "a", "c")

const test1 = res.a;
const test2 = res.b;
const test3 = res.c;

关于typescript - 如何创建原始类型和自定义类型的联合,并更改原始类型的某些属性并保持不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60777583/

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