gpt4 book ai didi

typescript - 重命名 typescript 对象类型的键

转载 作者:行者123 更新时间:2023-12-03 16:13:22 32 4
gpt4 key购买 nike

我有这个:

type Two = {
one: number,
two: string,
three: boolean
}

我希望它创建一个看起来像这样的类型:
type RenamedTwo = {
one: number,
two: string,
four: boolean // difference
}

尝试以这种方式创建它:
type Rename<T, K extends keyof T, N> = Pick<T, Exclude<keyof T, K>> & { [N]: T[K] }

尝试使用这种方式:
type Renamed = Rename<Two, 'three', 'four'>

但是TSlint将 [N]标记为错误并给出了以下错误消息:

[ts] A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type. [ts] 'N' only refers to a type, but is being used as a value here.

最佳答案

您还需要对重命名的属性使用映射类型:

type Two = {
one: number,
two: string,
three: boolean
}


type Rename<T, K extends keyof T, N extends string> = Pick<T, Exclude<keyof T, K>> & { [P in N]: T[K] }

type Renamed = Rename<Two, 'three', 'four'>

请注意,如果您提供更多属性,则此操作将无法按预期进行:
type Renamed = Rename<Two, 'two'  |'three' , 'four' | 'five'> // will be Pick<Two, "one"> & {
// four: string | boolean;
// five: string | boolean;
// }

关于typescript - 重命名 typescript 对象类型的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52702461/

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