gpt4 book ai didi

javascript - 如何使用 TS 为内置类型创建 polyfill

转载 作者:搜寻专家 更新时间:2023-10-30 21:12:34 25 4
gpt4 key购买 nike

我有几个 polyfill,我正在我的解决方案中使用它们。例如,Array.includes:

 if (![].includes) {
Array.prototype.includes = function(searchElement/*, fromIndex*/) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
var currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)
) {
return true;
}
k++;
}
return false;
};
}

但我想将我的 utils.js 迁移到 utils.ts(我从不使用 TS,所以我想玩它),我写了以下内容:

interface Array<T> {
includes(searchElement: T, fromIndex?: number): boolean;
}

if (!Array.prototype.hasOwnProperty('includes')) {
class MyArray<T> extends Array<T> {
includes(searchElement: T, fromIndex?: number): boolean {
const obj = Object(this);
const len = parseInt(obj.length) || 0;
if (len === 0) {
return false;
}
const n = fromIndex || 0;
var k: number;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
const currentElement = obj[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)
) {
return true;
}
k++;
}
return false;
}
}
}

Array.prototype.includes 在 IE 中仍然是 undefined。当然,因为 TS 正在扩展我的自定义类而不是原生的 Array:

var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
if (!Array.prototype.hasOwnProperty('includes')) {
var MyArray = (function (_super) {
__extends(MyArray, _super);
function MyArray() {
_super.apply(this, arguments);
}
MyArray.prototype.includes = function (searchElement, fromIndex) {
var obj = Object(this);
var len = parseInt(obj.length) || 0;
if (len === 0) {
return false;
}
var n = fromIndex || 0;
var k;
if (n >= 0) {
k = n;
}
else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
var currentElement = obj[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
return MyArray;
}(Array));
}

如何扩展 Array 本身?

最佳答案

而不是 class MyArray<T> extends Array<T> {做`Array.prototype.includes =/在这里插入你的函数/

更多

您还应该声明 includes作为 Array 的成员如果你需要 by extending lib.d.ts

关于javascript - 如何使用 TS 为内置类型创建 polyfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938802/

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