Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 键入assoc函数以正确推断新类型_Typescript - Fatal编程技术网

Typescript 键入assoc函数以正确推断新类型

Typescript 键入assoc函数以正确推断新类型,typescript,Typescript,我设置了assoc功能(将新键与对象上的新值关联): export const assoc=( newKey:PropertyKey, 新价值观:U, o:T, ) => ({ ……哦, [newKey]:newValue, }); 但我得到的类型是: T&{ [x:字符串]:U; } 我已尝试手动将输出类型指定为: {[key:K]:U} 但密钥必须是字符串或数字,这很公平 我还尝试了以下方法: export const assoc=( 纽基:K2, newValue:V, o:U, )

我设置了
assoc
功能(将新键与对象上的新值关联):

export const assoc=(
newKey:PropertyKey,
新价值观:U,
o:T,
) => ({
……哦,
[newKey]:newValue,
});
但我得到的类型是:

T&{
[x:字符串]:U;
}
我已尝试手动将输出类型指定为:

{[key:K]:U}
但密钥必须是字符串或数字,这很公平

我还尝试了以下方法:

export const assoc=(
纽基:K2,
newValue:V,
o:U,
):U&Record=>({
……哦,
[newKey]:newValue,
});
但这给了我一个错误:

类型'U&{[x:string]:V;}'不可分配给类型'U& 记录'。类型'U&{[x:string]:V;}'不可分配给 键入“记录”


我被困在正确的方式来键入这个;实际上,我只是想让编译器知道,它将具有输入对象的类型,仅使用新的键/值对进行扩展。有什么想法吗?

恐怕唯一的解决方案是类型断言
{[newKey]:newValue}
如果
newKey
是一个泛型类型参数,而不是
Record
@TitianCernicova Dragomir,那就推断出一个索引签名。非常感谢-很高兴知道,在这种情况下,我可能会使用类型断言