TS里能写这写代码吗 Objectprototypelog = function consolelogthis; const arr = 1 2; const dd = dd 1 ddd 2 ; const a = 1; ddlog; arrlog; alog;
可以写这段代码,但是在 TypeScript 中可能会提示错误,因为 TypeScript 会默认开启 strict 模式,禁止对原生对象进行扩展。如果需要在 TypeScript 中使用该代码,可以通过声明全局变量的方式,告诉 TypeScript 编译器该对象已经被定义过了。例如:
declare global { interface Object { log(): void; } }
Object.prototype.log = function () { console.log(this); };
const arr = [1, 2]; const dd = { dd: 1, ddd: 2 }; const a = 1; dd.log(); arr.log(); a.log();
原文地址: http://www.cveoy.top/t/topic/YJo 著作权归作者所有。请勿转载和采集!