“对象构造函数”类型上不存在React TypeScript属性“assign”

时间:2017-04-24 14:26:47

标签: reactjs typescript

我是React和TypeScript的新手,所以可能会有一些我错过的东西。我正在尝试执行以下操作:

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

我错过了什么?

1 个答案:

答案 0 :(得分: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元素。

相关问题