【问题标题】:React TypeScript Property 'assign' does not exist on type 'Object constructor'类型“对象构造函数”上不存在 React TypeScript 属性“分配”
【发布时间】:2017-09-21 07:03:16
【问题描述】:

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

我错过了什么?

【问题讨论】:

  • 这有点奇怪。你能提供更多的背景信息吗?例如。您正在使用它的组件,也可能是您的tsconfig?因为你的第一个代码 sn-p 应该没有问题。

标签: reactjs typescript


【解决方案1】:

Object.assignes6 功能,因此您需要定位es6

{
    "compilerOptions": {
        ...
        "target": "es6",
        ...
    }
}

如果您无法定位es6,但仍确定您的代码将在支持新的es6 功能的环境中运行,那么您可以使用该库:

{
    "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 文件中,编译器认为&lt;any&gt; 是一个html/react 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 2021-01-23
    • 2020-05-15
    • 1970-01-01
    • 2023-01-09
    • 2014-08-21
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多