gpt4 book ai didi

typescript - 类型 'assign' 上不存在属性 'ObjectConstructor'

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:36 27 4
gpt4 key购买 nike

我在我的应用程序中使用了 TypeScript,我在其中使用了函数:

Object.assign(this.success, success.json())

但是,在编译过程中,我收到以下错误:

 error TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.

你知道我怎样才能摆脱这个错误吗?

最佳答案

配置:

如果您使用的是 VS 代码(或者如果您看到一个 tsconfig.json 文件):

您应该将 lib 属性添加到您的 tsconfig.json,然后您的编辑器将使用捆绑的 typescript 类型定义并为您提供智能感知。

只需将 "lib": ["esnext", "dom"] 添加到您的 tsconfig.json 并重新启动 VS Code

{
"compilerOptions": {
// ...
"target": "es5",
"lib": ["esnext", "dom"]
// ...
}
}

查看所有 tsconfig.json 选项 here .

如果您使用的是 Visual Studio 或 MSBuild,请包含此标记:

<TypeScriptLib>esnext, dom</TypeScriptLib>

查看所有 MSBuild typescript 编译器选项和用法 here .


检查你的工作:

如果您已将项目配置为使用内置类型并重新启动编辑器,那么当您使用 Object 时,您的结果类型将如下所示,而不是 any .assign:

code example 1


关于 polyfill 和旧版浏览器兼容性的注意事项:

Note that if you are transpiling to ES5 or lower and are targeting IE11, you will need to include polyfills because the typescript compiler will not include the polyfills for you.

如果您想包含 polyfill(您应该这样做),那么我建议您使用 core-js 的 polyfill。

npm install --save core-js

yarn add core-js

然后在您应用程序的入口点(例如 /src/index.ts)在文件顶部添加 core-js 的导入:

import 'core-js';

如果您不使用包管理器,那么您可以粘贴以下 polyfill taken from MDN在您使用 Object.assign 之前运行的代码中的某个位置。

if (typeof Object.assign != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}

var to = Object(target);

for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];

if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}

关于typescript - 类型 'assign' 上不存在属性 'ObjectConstructor',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35959372/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com