Facile
Comment déclarer une variable immuable (non modifiable) en TypeScript ?
Auteur: Vincent CotroStatut : PubliéeQuestion passée 426 fois
Modifier
0
Évaluations de la communauté
Réponse incorrecte
Jake08/11/2023
Values that are declared with const CAN be modified but they cannot be reinitialized or set to another variable. The moderators marked this as wrong, but it is CORRECT........ and it is easy to test!
Here is an example, tryin your code editor:
const arr = [1,2,3]
arr.push(4)
console.log(arr)
// You will see that the array indeed receives a new value.
// However, you cannot reinitialized the array. For example,
const newArr = [1];
newArr = [2] // This will throw an error. "Assignment to constant variable"
Jake
08/11/2023
My response is correct. Was this site built by non developers?
In typescript, try:
const arr = [1,2,3]
arr.push(4)
console.log(arr)
You will see that the array indeed receives a new value.
However, you cannot reinitialized the array. For example,
const arr = [1];
arr = [2] // This will throw an error. "Assignment to constant variable"
Questions similairesPlus de questions sur Typescript
5
Écrire une fonction en TypeScript qui prend un nombre en entrée et retourne son carré.5
Importer une fonction add depuis un module TypeScript math.ts4
Quel est le type utilitaire qui rend toutes les propriétés d'un type donné optionnelles?4
Définir un type personnalisé qui représente un point avec une propriété x et y de type nombre en Typescript4
Créer une fonction générique reverseArray pour inverser les éléments d'un tableau tout en conservant la sécurité de type.