私は私のソリューションで使用しているいくつかのポリフィルを用意しています。たとえば、Array.includes
:ビルドタイプのポリフィルをTSで作成する方法
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;
};
}
しかし、私は(私はそれを再生したい私は決してユーザーTS)私のutils.js
utils.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
をundefined
IEで。 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
自体が拡張していますか?
[TypeScript:組み込み型を補完する]の可能な複製(0120-17753) –
@MikeMcCaughanリンクありがとうございます。しかし、1つの疑問が残っています。例えば、[ここ](http://typescript.codeplex.com/workitem/4)は '配列'拡張ですが、強く型付けされた拡張については何もありません( 'Array' –
それはあなたの質問についてではありません。あなたのタイトル(または重複のタイトル)を検索するだけで、たくさんのヒットを得ることができます。 –