2017-09-17 92 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