繁体   English   中英

object 转换中的通用返回类型

[英]Generic return type in object transformation

我有一个 function 接受一个 object 并返回一个具有附加属性的新的。 而且我无法弄清楚为什么这种通用类型不起作用。

const obj = { name: 'hello', id: 1 };

const transformObj = <T extends { name: string }>({ name, ...rest }: T): T & { newName: string } => ({
    name,
    newName: name + '1',
    ...rest,
});

游乐场链接

它返回此错误

Type '{ name: string; newName: string; } & Pick<T, Exclude<keyof T, "name">>' is not assignable to type 'T & { newName: string; }'. Type '{ name: string; newName: string; } & Pick<T, Exclude<keyof T, "name">>' is not assignable to type 'T'. '{ name: string; newName: string; } & Pick<T, Exclude<keyof T, "name">>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ name: string; }'.

这就是为什么它不能像所写的那样工作。 注意obj中的{ newName: number } 这个 object 确实满足约束<T extends { name: string }> ,但是试图将它与{ newName: string }相交会产生矛盾。

const obj = { name: 'hello', /**/ newName: 10 /**/, id: 1 };

这为您提供了所需的类型,方法是从keyof rest中删除"newName"并进行解构,然后将其作为string添加回来。

const transformObj = <T extends { name: string, newName?: unknown }>({ name, newName, ...rest }: T): typeof rest & { name: string, newName: string } => ({
    ...rest,    
    name,
    newName: name + '1',
});

暂无
暂无

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

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