简体   繁体   English

TypeScript:重命名一个属性的另一种类型的类型

[英]TypeScript: Type of another type with one property renamed

Is it possible to create a function that transform an object by renaming one property, and properly returns the type of this?是否可以通过重命名一个属性来创建一个转换对象的函数,并正确返回 this 的类型?

Example:例子:

My input type:我的输入类型:

type In = {
  foo: string;
  bar: number;
};

const in: In = {foo: 'hello', bar: 42};

I want to call a function that renames foo to convertedFoo , while maintaining its type (string), and has a return type that reflects this object.我想打电话给一个重命名功能fooconvertedFoo ,同时保持其类型(字符串),并具有反映该对象返回类型。

const out = convert(in, 'foo', 'convertedFoo')

Now I want out to be {convertedFoo: 'hello', bar: 42}现在我想out{convertedFoo: 'hello', bar: 42}

I tried我试过

function convert<T>(obj: T, oldProp: keyof T, newProp: string): Omit<T, oldProp> & {[newProp]: T[oldProp]} {
    const {[oldProp]: id, ...rest} = obj;

    return {...rest, [newProp]: id};
}

But this (obviously) doesn't work since oldProp cannot be passed to Omit dynamically, and newProp cannot be used as a computer property name in a literal.但这(显然)不起作用,因为oldProp不能动态传递给Omit ,并且newProp不能用作文字中的计算机属性名称。

Is this at all possible to accomplish?这完全有可能实现吗?

Try this:尝试这个:

const in_var = {
    foo: 'hello',
    bar: 42,
    step: true
}; // in is keyword
function convert<T, OldProp extends keyof T, NewProp extends string>(obj: T, oldProp: OldProp, newProp: NewProp) {
    const {
        [oldProp]: id,
        ...rest
    } = obj;

    return {
        ...rest,
        [newProp]: id
    } as Omit<T, OldProp> & Record<NewProp, T[OldProp]>;
}
var a = convert(in_var, "foo", "foo_new").foo_new; // intellisense works! (I trust you use Visual Studio Code)

Firstly, in is invalid variable name, it's keyword.首先,in 是无效的变量名,它是关键字。 Then you cannot use {[newProp]: T[oldProp]} because you mix values and types.那么你不能使用{[newProp]: T[oldProp]}因为你混合了值和类型。 Better was {[x: NewProp]: T[OldProp]} but TypeScript throws an error, because it doesn't know if NewProp is string or number.更好的是{[x: NewProp]: T[OldProp]}但 TypeScript 会抛出错误,因为它不知道 NewProp 是字符串还是数字。 Use Record.使用记录。 I spend one hour for answer, I trust it's correct.我花了一个小时来回答,我相信它是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM