Typescript 对象转换中的泛型返回类型

Typescript 对象转换中的泛型返回类型,typescript,Typescript,我有一个函数,它接受一个对象并返回一个具有附加属性的新对象。我也不明白为什么这种通用类型不起作用 const obj = { name: 'hello', id: 1 }; const transformObj = <T extends { name: string }>({ name, ...rest }: T): T & { newName: string } => ({ name, newName: name + '1', ...rest

我有一个函数,它接受一个对象并返回一个具有附加属性的新对象。我也不明白为什么这种通用类型不起作用

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

const transformObj = <T extends { name: string }>({ name, ...rest }: T): T & { newName: string } => ({
    name,
    newName: name + '1',
    ...rest,
});
const obj={name:'hello',id:1};
const transformObj=({name,…rest}:T):T&{newName:string}=>({
名称
newName:name+'1',
休息
});

它返回这个错误

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; }'.

类型“{name:string;newName:string;}&Pick”不能分配给类型“T&{newName:string;}”。类型“{name:string;newName:string;}&Pick”不可分配给类型“T”{name:string;newName:string;}&Pick'可分配给类型为'T'的约束,但'T'可以用约束{name:string;}的不同子类型实例化。

以下是它无法按编写方式工作的原因。注意
obj
中的
{newName:number}
。此对象确实满足约束
,但尝试将其与
{newName:string}
相交会产生矛盾

const obj={name:'hello',/**/newName:10/**/,id:1};
这将为您提供所需的类型,方法是通过分解结构从rest的键中删除
“newName”
,然后将其作为
字符串添加回来

const transformObj=({name,newName,…rest}:T):rest的类型&{name:string,newName:string}=>({
休息
名称
newName:name+'1',
});

很有趣。但是如果问题出在
newName
上,为什么它也会发生在?(有趣的是,我确实尝试了一种在泛型约束中使用
newName
的方法,但我做到了
newName:never
。你的
newName?:unknown
更有意义。)我认为这只是编译器的一个限制;它不能告诉你,
{name:string;}&Pick
等同于t given
。嗯,你的简化似乎可以编译,但它是--你需要把
newName
放在
…rest
之后。不,这似乎很好,我用
ctrl+enter
运行它,得到了
{newName:“hello1”,“id”:1,“name:“hello”}
@JoshWilson-示例不清楚。问题在于结果的类型:请注意,
result.newName
的类型是
never
。但是你答案中的密码。。。