Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.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中文字的推断类型?_Typescript_Type Inference - Fatal编程技术网

是否可以修改TypeScript中文字的推断类型?

是否可以修改TypeScript中文字的推断类型?,typescript,type-inference,Typescript,Type Inference,考虑以下代码,该代码尝试有条件地向具有推断类型的对象添加属性: const foo = { a: 1, b: 2, }; if (bar) { foo.c = 3; // Error: Property 'c' does not exist on type '{ a: number; b: number; }'.(2339) } 可以通过将foo的类型显式声明为{a:number;b:number;c?:number;}或使用排列有条件地添加c来删除错误: const

考虑以下代码,该代码尝试有条件地向具有推断类型的对象添加属性:

const foo = {
    a: 1,
    b: 2,
};

if (bar) {
    foo.c = 3; // Error: Property 'c' does not exist on type '{ a: number; b: number; }'.(2339)
}
可以通过将
foo
的类型显式声明为
{a:number;b:number;c?:number;}
或使用排列有条件地添加
c
来删除错误:

const foo = {
    a: 1,
    b: 2,
    ...(bar ? { c: 3 } : {}),
};
但是,假设我们希望保留原始代码结构,但也希望避免显式声明可以推断的属性。有什么解决方案可以同时满足这两个条件吗?例如,是否可以以某种方式调整推断类型,例如:

const foo = {
    a: 1,
    b: 2,
} as { ...; c?: number; }; // Example, does not work

这并不漂亮,但它是有效的:
a
b
的属性类型是推断的,不必重复声明

function withMissingProps<T>() {
  return function<S>(obj: S): S & Partial<T> {
    return obj;
  }
}

const foo = withMissingProps<{ c: number }>()({
  a: 1,
  b: 2
});

if(Math.random() > 0.5) {
  foo.c = 1;
}
函数withMissingProps(){
返回函数(obj:S):S&Partial{
返回obj;
}
}
const foo=withMissingProps()({
答:1,,
b:2
});
if(Math.random()>0.5){
foo.c=1;
}
声明属性和推断属性分别有两个类型参数,
T
S
。不幸的是,如果一个函数有两个类型参数,那么必须同时提供这两个参数或同时推断这两个参数;解决方案是curry函数,尽管这意味着额外的一对括号


我还发现了这个黑客,不幸的是它编译成了
Object.assign
,因此运行时成本非零:

const foo = {
  a: 1,
  b: 2,
  ...{} as {
    c?: number,
  },
};