配置:
如果您使用的是 VS 代码(或者如果您看到 tsconfig.json 文件):
您应该将lib 属性添加到您的tsconfig.json,然后您的编辑器将使用捆绑的打字稿类型定义并为您提供智能感知。
只需将 "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.assign 时,生成的类型将如下所示,而不是 any:
关于 polyfill 和旧版浏览器兼容性的说明:
请注意,如果您要转译到 ES5 或更低版本并以 IE11 为目标,则需要包含 polyfill,因为 typescript 编译器不会为您包含 polyfill。
如果您想包含 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
});
}