javascript - TypeScript vrátiť nemenné/const/readonly pole


Chcem mať funkciu, ktorá vracia pole, ale chcem, aby vrátené pole bolo iba na čítanie, takže by som mal dostať upozornenie/chybu, keď sa pokúsim zmeniť jeho obsah.

function getList(): readonly number[] {
   return [1,2,3];
}


const list = getList();
list[2] = 5; // This should result in a compile error, the returned list should never be changed

Je to možné dosiahnuť v TypeScripte?

Odpoveď č. 1

Zdá sa, že to funguje...

function getList(): ReadonlyArray<number> {
    return [1, 2, 3];
}

const list = getList();

list[0] = 3; // Index signature in type 'ReadonlyArray<number>' only permits reading.

Vyskúšajte to na ihrisku

ReadonlyArray<T> je implementované takto:

interface ReadonlyArray<T> {
    readonly [n: number]: T;
    // Rest of the interface removed for brevity.
}

Odpoveď č. 2

Samotný kód od OP teraz funguje, pretože TypeScript 3.4 zaviedol novú syntax pre ReadonlyArray:

Hoci je dobré používať ReadonlyArray namiesto Array, keď nie je zamýšľaná žiadna mutácia, často je to nepraktické, pretože polia majú krajšiu syntax. Konkrétne, number[] je skrátená verzia Array<number>, rovnako ako Date[] je skratka pre Array<Date>.

TypeScript 3.4 zavádza novú syntax pre ReadonlyArray pomocou nového modifikátora readonly pre typy polí.

Tento kód teraz funguje podľa očakávania:

function getList(): readonly number[] {
   return [1,2,3];
}

const list = getList();
list[2] = 5; // <-- error

Detské ihrisko.

Súvisiace články