Does TypeScript have extensions like Kotlin?

Kotlin has a feature called Extensions , which allows you to "extend" any type (including built-in types) without actually extending it.

For instance:

function Array<T>.swap(i1: number, i2: number) {
    let tmp = this[i1]
    this[i1] = this[i2]
    this[i2] = tmp
}

let list = [1, 2, 3]
list.swap(0, 2)
console.log(list) // => 3, 2, 1

The interesting part is that, unlike the usual extension of the basic types, this approach does not change the array or the chain of its prototypes .

The generated JS code will look something like this:

function _array_extensions_swap(i1, i2) {
    let tmp = this[i1]
    this[i1] = this[i2]
    this[i2] = tmp
}

let list = [1, 2, 3]
_array_extensions_swap(list, 0, 2)
console.log(list) // => 3, 2, 1

I wonder if it is possible to do the same in TypeScript, or if there are plans to support this in the future?

+4
source share
1 answer

, , , , .
, kotlin, , ​​ javascript ( typescript) :

let list = [1, 2, 3] as number[] & { swap(i1: number, i2: number): void };
list.swap = function (i1: number, i2: number) {
    let tmp = this[i1]
    this[i1] = this[i2]
    this[i2] = tmp;
}

list.swap(0, 2);
console.log(list); // [3, 2, 1]

factory :

function extend<T>(list: T[]): T[] & { swap(i1: number, i2: number): void } {
    (list as T[] & { swap(i1: number, i2: number): void }).swap = function (i1: number, i2: number) {
        let tmp = this[i1]
        this[i1] = this[i2]
        this[i2] = tmp;
    }

    return list as T[] & { swap(i1: number, i2: number): void };
}

let list = extend([1, 2, 3]);
list.swap(0, 2);
console.log(list); // [3, 2, 1]

( )

0

Source: https://habr.com/ru/post/1663403/


All Articles