React TypeScript 属性 'assign' 在类型'Object constructor' 上不存在



我是React和TypeScript的新手,因此我可能错过了一些明显的东西。我正在尝试执行以下操作:

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

我在我的.tsx文件中获取此错误:Property 'assign' does not exist on type 'Object constructor'.

找到了此线程并尝试了:

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

我错过了什么?

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。

至于您尝试过的铸件,您不能在tsx文件中使用这种形式的铸造形式,您需要执行此操作:

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

因为在tsx文件中,编译器认为<any>是HTML/React元素。

相关内容

最新更新