我是React和TypeScript的新手,因此我可能错过了一些明显的东西。我正在尝试执行以下操作:
const props = Object.assign({}, this.props, {
loaded: this.state.loaded
});
我在我的.tsx
文件中获取此错误:Property 'assign' does not exist on type 'Object constructor'.
找到了此线程并尝试了:
const props = (<any>Object).assign({}, this.props, {
loaded: this.state.loaded
});
给了我这个错误: Property 'any' does not exist on type 'JXS.IntrinsicElements'.
我还尝试了返回 Unexpected modifier
以供声明。
declare interface ObjectConstructor {
assign(target: any, ...sources: any[]): any;
}
我错过了什么?
Object.assign
是es6
功能,因此您需要定位es6
:
{
"compilerOptions": {
...
"target": "es6",
...
}
}
如果您无法定位es6
,但仍然可以确定您的代码将在支持新es6
功能的环境中运行,则可以使用LIB:
{
"compilerOptions": {
...
"target": "es5", // for example
"lib": ["DOM", "ES6", "ScriptHost"],
...
}
}
另一个选择是自己添加此娱乐性。
您需要添加定义(从lib.es6.d.ts复制(:
interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
assign(target: any, ...sources: any[]): any;
}
然后polyfill。
至于您尝试过的铸件,您不能在tsx
文件中使用这种形式的铸造形式,您需要执行此操作:
const props = (Object as any).assign({}, this.props, {
loaded: this.state.loaded
});
因为在tsx
文件中,编译器认为<any>
是HTML/React元素。