2017-04-24 100 views
0

我是React和TypeScript的新手,所以可能会有一些显而易见的错误。我试图做到以下几点:React TypeScript属性'assign'在类型'Object constructor'上不存在

const props = Object.assign({}, this.props, { 
    loaded: this.state.loaded 
}); 

我在.tsx文件中得到这个错误:Property 'assign' does not exist on type 'Object constructor'.

发现this thread和尝试:

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

我错过了什么?

+0

这有点奇怪。你可以提供更多的背景吗?例如。你使用它的组件,也可能是你的'tsconfig'?因为第一个代码片段不应该有问题。 –

回答

2

Object.assignes6功能,因此你需要的目标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 it

至于你的努力,你不能用这种形式铸造里面tsx文件的铸件,你需要这样做:

const props = (Object as any).assign({}, this.props, { 
    loaded: this.state.loaded 
}); 

由于tsx文件编译器认为<any>作为html/react元素。

相关问题