2017-09-17 83 views
0

打字稿使用的代碼如下:Spead語法不能打字稿的類

interface ChildrenPropsType { 
    children: Array<TheElement<any>> 
} 
class TheElement<PropsType extends object> { 
    props: PropsType & ChildrenPropsType; 
    constructor(props: PropsType, children: ChildrenPropsType) { 
    this.props = { 
     children:children, 
     ...props 
    } 
    } 
} 

Error: TS2698:Spread types may only be created from object types.

如何解決這個問題?


tsc --version 
Version 2.5.2 
+0

傳播目前不支持泛型。你可以通過'......道具任意'來解決這個問題。 [相關問題](https://github.com/Microsoft/TypeScript/issues/10727) –

回答

0

問題在https://github.com/Microsoft/TypeScript/issues/12759登錄GitHub上

一個解決方法是直接使用Object.assign() - 只記得,不像傳播經營者,assign修改的第一個參數 - 所以總是傳遞一個空對象:

interface ChildrenPropsType { 
    children: Array<TheElement<any>> 
} 

class TheElement<PropsType> { 
    props: PropsType & ChildrenPropsType; 
    constructor(props: PropsType, children: ChildrenPropsType) { 
    this.props = Object.assign(
     {}, 
     children, 
     props 
    ); 
    } 
} 

您可能還需要填充工具Object.assignsee browser support)。

+0

我發現我可以使用 'this.props = { 孩子, ... 道具 }' – xiang