2017-04-24 97 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元素。

相關問題