Thierry  Perret

Thierry Perret

1661784423

Top 10 Des Astuces Rapides Que J'ai Apprises Avec TypeScript

TypeScript offre tout ce que JavaScript fait, plus le typage statique. Outre le système de type de TypeScript, ce qui m'a fait tomber amoureux, c'est qu'il documente votre code. Découvrez ces 10 conseils qui vous aideront à tomber amoureux vous aussi !

En un mot, TypeScript est un langage de programmation qui offre toutes les fonctionnalités JavaScript, mais avec le typage statique activé chaque fois que vous le souhaitez. Le code est compilé en JavaScript brut, et le langage, maintenu par Microsoft, gagne en popularité chaque année, car de plus en plus de frameworks populaires s'en servent (Vue 3, AdonisJS, NestJS…).

Mais, outre le système de type de TypeScript, ce qui m'a fait tomber amoureux de ce langage, c'est qu'il documente votre code. Vous pouvez voir en un coup d'œil de quel type doit être une variable, l'argument d'une fonction ou sa réponse. Cela rend l'expérience du développeur tellement plus agréable. 🧙‍♂️

Cet article est écrit pour les personnes qui connaissent déjà TypeScript. Je souhaite partager 10 astuces rapides que j'ai apprises tout au long de mon parcours de développeur. 😉

1. Utilisez le type inconnu avant de choisir par défaut Any

Nous savons tous que l'utilisation du anymot-clé est en quelque sorte diabolique. 😈

Heureusement, TypeScript 3.0 a introduit un nouveau mot-clé appelé unknown.

La principale différence entre anyet unknownest que le unknowntype ne peut être attribué qu'au anytype et au unknowntype lui-même. Ainsi, c'est un type beaucoup moins permissif et un excellent substitut à any, car il rappellera constamment à votre éditeur que vous devez le remplacer par quelque chose de plus explicite. En passant de anyà unknown, on n'autorise (presque) rien au lieu de tout autoriser.

Voici un exemple rapide pour illustrer ce que je veux dire :

let  unknownValue: unknown;
let  anyValue: any;

let  unknownValue2: unknown = unknownValue; // This is fine
let  anyValue2: any = unknownValue; // This is fine

let  booleanValue: boolean = unknownValue; // Type 'unknown' is not assignable to type 'boolean'.
let  booleanValue2: boolean = anyValue; // While this works

let  numberValue: number = unknownValue; // Type 'unknown' is not assignable to type 'number'.
let  numberValue2: number = anyValue; // While this works

let  stringValue: string = unknownValue; // Type 'unknown' is not assignable to type 'string'.
let  stringValue2: string = anyValue; // While this works

let  objectValue: object = unknownValue; // Type 'unknown' is not assignable to type 'object'.
let  objectValue2: object = anyValue; // While this works

let  arrayValue: any[] = unknownValue; // Type 'unknown' is not assignable to type 'any[]'.
let  arrayValue2: any[] = anyValue; // While this works

let  functionValue: Function = unknownValue; // Type 'unknown' is not assignable to type 'Function'.
let  functionValue2: Function = anyValue; // While this works

Une autre chose que j'aime faire dans mes projets est d'activer noImplicitAny. Cet indicateur indiquera à TypeScript d'émettre une erreur chaque fois que quelque chose a le type any(défini par vous ou déduit par TypeScript). Plus de détails dans la documentation officielle .

2. Le type Jamais peut être pratique pour la gestion des erreurs

Il existe également un autre type que nous n'utilisons jamais lorsque nous commençons à jouer avec TypeScript : le mot- neverclé. En un mot, il représente le type de valeurs qui ne se produisent jamais.

Il y a quelque temps, j'ai trouvé que ce mot-clé peut être pratique lors de l'écriture de fonctions qui déclenchent une ou plusieurs erreurs et ne retournent jamais rien.

function  throwErrors(statusCode: number): never {
if (statusCode >= 400 && statusCode <= 499) {
throw  Error("Request Error");
}

throw  Error("Something wrong happened.");
}

Nous pouvons également utiliser ce type à notre avantage en nous assurant que chaque situation critique est gérée dans nos fonctions. Voici un exemple rapide de cas où nous avons oublié de tester le cas pour l'espèce humaine.

interface  Dwarf {
weapon: "axe";
}

interface  Elf {
weapon: "bow";
}

interface  Man {
weapon: "sword";
}

type  Specy = Dwarf | Elf | Man;

function  whatIsThatGandalf(specy: Specy) {
let  _ensureAllCasesAreHandled: never;

if (specy.weapon === "axe") {
return  "This is a dwarf";
} else  if (specy.weapon === "bow") {
return  "This is an elf";
}

// ERROR: Type 'Man' is not assignable to type 'never'
_ensureAllCasesAreHandled = specy;
}

3. Interfaces vs Types

Nous entendons souvent cette question de la part de personnes qui viennent de commencer leur parcours TypeScript : quelle est la différence entre une interface et un type ? Dois-je utiliser les deux ? 🤔

Il m'a fallu quelques semaines, au début, pour me fixer une règle car on peut souvent faire la même chose avec les deux. Voici comment je résumerais : Quand je travaille avec des classes ou des objets, j'utilise une interface. Quand je ne le suis pas, j'utilise un type. Cela aiderait si vous vous souveniez que la chose la plus importante est d'être cohérent avec vos choix dans votre base de code.

Bien sûr, il existe aussi quelques différences subtiles entre les deux, comme expliqué dans cette superbe vidéo . Par exemple, une interface peut étendre d'autres interfaces, alors que vous avez besoin d'une union ou d'une intersection pour fusionner deux types ensemble (car ils sont statiques).

De plus, d'après mon expérience, lorsque je traite des types, le message d'erreur peut généralement être plus brutal pour comprendre quand quelque chose ne va pas.

Une autre chose à garder à l'esprit est que la documentation TypeScript vous encourage à utiliser une interface lorsque cela est possible, surtout si vous écrivez une bibliothèque qui exporte un type. La raison en est qu'une interface peut être étendue pour répondre aux besoins de l'application qui utilise votre code.

4. Apprenez à utiliser les types génériques

Les types génériques sont pratiques. Plus vous vous familiarisez avec TypeScript, plus vous les utilisez. Ils permettent à votre code d'être plus flexible en vous permettant de définir vous-même le type. Un exemple peindra mille mots. 😃

Disons que nous voulons geler ou transformer toutes les propriétés d'un objet en propriétés en lecture seule. Eh bien… nous pourrions faire quelque chose comme ça.

interface  Elf {
name: string;
weapon: "bow";
}

const  myElf: Elf = {
name:  "Legolas",
weapon:  "bow",
};

const  freezedElf = Object.freeze(myElf);

// ERROR: Cannot assign to 'name' because it is a read-only property.
freezedElf.name = "Galadriel";

Maintenant, utilisons un type générique pour faire la même chose.

interface  Elf {
name: string;
weapon: "bow";
}

const  myElf: Elf = {
name:  "Legolas",
weapon:  "bow",
};

type  Freeze<T> = {
readonly [P  in  keyof  T]: T[P];
};

const  freezedElf: Freeze<Elf> = myElf;

// ERROR: Cannot assign to 'name' because it is a read-only property.
freezedElf.name = "Galadriel";

// For your information, the generic type Freeze already exists in TypeScript and is called Readonly.

// https://www.typescriptlang.org/docs/handbook/utility-types.html

// So both are equivalent
const  freezedElf: Freeze<Elf> = myElf;
const  freezedElf: Readonly<Elf> = myElf;

Si vous vous posez la question, l' keyofopérateur prend un type d'objet et produit une chaîne ou une union numérique littérale de clés de liste.

Comme vous pouvez le voir dans l'exemple ci-dessus, ce qui est remarquable, c'est que peu importe la forme de l'objet, nous pouvons créer un autre type ( Freeze<Elf>) qui inclura toutes les propriétés définies en lecture seule.

Voici un autre type générique qui définira toutes les propriétés de l'objet comme non en lecture seule.

type  Writable<T> = {
-readonly [P  in  keyof  T]: T[P];
};

Un dernier exemple ici est une fonction utilisant un type générique qui renvoie le dernier élément d'un tableau.

const  getLastElement = <T>(array: T[]) => {
return  array[array.length - 1];
};

5. Le type d'utilitaire partiel pourrait être votre nouveau meilleur ami

Que se passe-t-il si nous souhaitons créer un nouveau type basé sur un autre type mais avec toutes ses propriétés définies sur facultatives. Comment pourrions-nous faire cela ? 🤔

TypeScript est livré avec un utilitaire que j'utilise chaque semaine appelé Partial<Type>. Voici comment cela fonctionne.

interface  Elf {
name: string;
weapon: "bow";
lifepoints: number;
}

type  PartialElf = Partial<Elf>;

// We can omit the weapon attribute as all properties are now optional

const  partialElf: PartialElf = {
name:  "Legolas",
lifepoints:  100,
};

// This is how it is coded behind the curtain
type  Partial<T> = {
[P  in  keyof  T]?: T[P];
};

Génial, non ? Plongeons maintenant dans d'autres types d'utilitaires que vous aimerez utiliser dans votre projet. 😃

6. Autres types d'utilitaires à connaître

Vous avez appris Partial<Type>à construire un type avec toutes les propriétés de Typela valeur facultative. Mais il y en a plus. Voici ceux que j'utilise souvent :

  • Required<Type>: construit un type composé de toutes les propriétés de Typeset to required. Comme vous pouvez le deviner, c'est l'opposé de Partial.
interface  Properties {
a?: number;
b?: string;
}

const  object: Properties = { a:  5 };

// ERROR: Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Properties>'.
const  object2: Required<Properties> = { a:  5 };
  • Readonly<Type>: construit un type avec toutes les propriétés de Typeset en lecture seule, ce qui signifie que les propriétés du type construit ne peuvent pas être réaffectées.
interface  Todo {
title: string;
}

const  todo: Readonly<Todo> = {
title:  "Learn Kendo UI",
};

// ERROR: Cannot assign to 'title' because it is a read-only property.
todo.title = "Hello";
  • Pick<Type, Keys>: construit un type en sélectionnant l'ensemble de propriétés Keys(littéral de chaîne ou union de littéraux de chaîne) dans Type.
interface  Todo {
title: string;
description: string;
completed: boolean;
}

type  TodoPreview = Pick<Todo, "title" | "completed">;

const  todo: TodoPreview = {
title:  "Learn DevCraft",
completed:  false,
};
  • Omit<Type, Keys>: construit un type en sélectionnant toutes les propriétés Typepuis en les supprimant Keys(littéral de chaîne ou union de littéraux de chaîne).
interface  Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}

type  TodoPreview = Omit<Todo, "description">;

const  todo: TodoPreview = {
title:  "Learn Kendo UI",
completed:  true,
createdAt:  1615277055442,
};
  • NonNullable<Type>: Construit un type en excluant nullet undefinedà partir de Type.
// T will be equivalent to string | number
type  T = NonNullable<string | number | undefined | null>;

Pour parcourir la liste complète des types d'utilitaires disponibles dans le monde, rendez -vous sur la documentation officielle .

7. Utilisez des gardes de type pour accéder à une propriété en toute sécurité

Le code à l'épreuve des balles utilise beaucoup les gardes de type. TypeScript permet de savoir plus facilement quand nous devons en utiliser un. 😍

Pour résumer, les gardes de type permettent de vérifier si un objet appartient au bon type. C'est une protection que nous utilisons dans notre code pour nous assurer que rien de mal ne se produit. Ce qui est excellent avec TypeScript, c'est que, avec les erreurs affichées directement dans l'éditeur, on peut deviner quand ajouter des gardes de type.

Voici quelques protections de type standard que vous pouvez utiliser.

  • typeof: L' typeofopérateur renvoie une chaîne indiquant le type de l'opérande non évalué.
function  stringOrNumber(x: number | string) {
if (typeof  x === "string") {
return  "I am a string";
}

return  "I am a number";
}
  • instanceof: L' instanceofopérateur teste pour voir si la propriété prototype d'un constructeur apparaît n'importe où dans la chaîne de prototypes d'un objet. La valeur de retour est une valeur booléenne.
class  Dwarf {
weapon = "axe";
}

class  Elf {
weapon = "bow";
}

function  dwarfOrElf(specy: Dwarf | Elf) {
if (specy  instanceof  Dwarf) {
return  "I am a dwarf";
}

return  "I am an elf";
}
  • in: L' inopérateur renvoie true si la propriété spécifiée se trouve dans l'objet spécifié ou sa chaîne de prototypes.
interface  Dwarf {
weapon: "axe";
lifepoints: number;
}

interface  Elf {
weapon: "bow";
}

function  dwarfOrElf(specy: Dwarf | Elf) {
if ("lifepoints"  in  specy) {
return  "I am a dwarf";
}

return  "I am an elf";
}
  • Protections de type définies par l'utilisateur.
interface  Dwarf {
weapon: "axe";
lifepoints: number;
}

interface  Elf {
weapon: "bow";
}

function  isDwarf(specy: any): specy  is  Dwarf {
return  specy.lifepoints !== undefined;
}

function  dwarfOrElf(specy: Dwarf | Elf) {
if (isDwarf(specy)) {
return  "I am a dwarf";
}

return  "I am an elf";
}

8. Les décorateurs personnalisés peuvent rendre votre code plus facile à lire (l'exemple de la fonction de synchronisation)

J'aime quand j'utilise un cadre ou une bibliothèque qui fait bon usage des décorateurs. Alors que certaines personnes pensent qu'elles sont un anti-modèle et qu'elles ne devraient pas être utilisées, la réalité est un peu plus complexe. Ils peuvent souvent rendre le code plus facile à lire et plus rapide à écrire. Les frameworks comme AdonisJS, NestJS ou encore Angular font beaucoup appel aux décorateurs.

Les décorateurs peuvent être appliqués aux définitions de classe, aux propriétés, aux méthodes, aux accesseurs et aux paramètres. Ils représentent des fonctions qui modifieront le comportement de votre code.

Ils sont faciles à écrire. Voici comment nous pouvons créer un décorateur qui calculera le temps d'exécution d'une fonction.

function  time(name: string) {
return  function (target, propertyKey: string, descriptor: PropertyDescriptor) {
const  fn = descriptor.value;

descriptor.value = (...args) => {
console.time(name);
const  v = fn(...args);
console.timeEnd(name);
return  v;
};
};
}

class  Specy {
@time("attack")
attack() {
// ...
}
}

Vous pouvez avoir un avertissement dans votre éditeur car la prise en charge des décorateurs expérimentaux est une fonctionnalité susceptible de changer dans une future version. Définissez l'option "experimentalDecorators" dans votre tsconfigou jsconfigpour supprimer cet avertissement.

Si vous voulez en savoir plus sur les décorateurs, vous devriez regarder cette superbe vidéo de Fireship (qui est aussi une excellente chaîne de codage à laquelle vous devriez vous abonner 😃).

Un mot d'avertissement : les classes héritées recevront les fonctionnalités du décorateur.

9. Utilisez strictNullChecks et noUncheckedIndexAccess

Il y a deux drapeaux que j'active habituellement dans mon fichier de configuration TypeScript : strictNullCheckset noUncheckedIndexAccess.

  • strictNullChecks: Par défaut, nullet undefinedsont assignables à tous les types dans TypeScript. Avec ce drapeau activé, ils ne le seront pas.
let  foo = undefined;

foo = null; // Will trigger an error

let  foo2: number = 123;

foo2 = null; // Will trigger an error
foo2 = undefined; // Will trigger an error
  • noUncheckedIndexAccess: TypeScript possède une fonctionnalité appelée signatures d'index. Ces signatures sont un moyen de signaler au système de type que les utilisateurs peuvent accéder à des propriétés nommées arbitrairement. Avec ce drapeau activé, ils ne pourront pas le faire.
const  nums = [0, 1, 2];
const  example: number = nums[4]; // WIll trigger an error

10. Utilisez noImplicitOverride (en particulier pour les fonctions fictives)

C'est probablement le conseil le plus utile de cette liste pour les personnes qui écrivent beaucoup de tests.

je vais m'expliquer. Lorsque nous créons des fonctions et des classes moqueuses pour vérifier que notre code se comporte correctement, nous ne voulons pas que les gens renomment une fonction à l'intérieur de cette classe initiale sans être avertis qu'ils doivent également la modifier à l'intérieur de la classe moqueuse. Eh bien… TypeScript vous aidera avec cela.

La première chose à faire pour résoudre ce problème est d'activer noImplicitOverridedans votre fichier de configuration TypeScript et d'utiliser le mot- overrideclé.

class  Specy {
lifepoints = 10;

heal(lifepoints: number) {
this.lifepoints += lifepoints || 10;
}
}

class  MockSpecy  extends  Specy {
override  heal(lifepoints) {
console.log("Let's override the heal method");
}
}

Si quelqu'un modifie la healfonction dans healingla Specyclasse, TypeScript affichera une erreur dans la MockSpecyclasse pour nous dire que nous devons également mettre à jour la méthode ici.

Emballer

Tu l'as fait! Voici dix conseils rapides sur TypeScript que je voulais partager avec vous. 😇

Un dernier conseil est que si vous souhaitez approfondir vos connaissances sur ce magnifique langage, vous devez choisir un framework basé sur celui-ci et plonger dans sa base de code, quelque chose comme Nest, Adonis ou Vue 3. Plus vous lisez le code TS, plus plus vous découvrirez de grandes choses que vous pouvez faire avec.

Lien : https://www.telerik.com/blogs/10-quick-tips-learned-using-typescript

#typescript #javascript

What is GEEK

Buddha Community

Top 10 Des Astuces Rapides Que J'ai Apprises Avec TypeScript
Thierry  Perret

Thierry Perret

1661784423

Top 10 Des Astuces Rapides Que J'ai Apprises Avec TypeScript

TypeScript offre tout ce que JavaScript fait, plus le typage statique. Outre le système de type de TypeScript, ce qui m'a fait tomber amoureux, c'est qu'il documente votre code. Découvrez ces 10 conseils qui vous aideront à tomber amoureux vous aussi !

En un mot, TypeScript est un langage de programmation qui offre toutes les fonctionnalités JavaScript, mais avec le typage statique activé chaque fois que vous le souhaitez. Le code est compilé en JavaScript brut, et le langage, maintenu par Microsoft, gagne en popularité chaque année, car de plus en plus de frameworks populaires s'en servent (Vue 3, AdonisJS, NestJS…).

Mais, outre le système de type de TypeScript, ce qui m'a fait tomber amoureux de ce langage, c'est qu'il documente votre code. Vous pouvez voir en un coup d'œil de quel type doit être une variable, l'argument d'une fonction ou sa réponse. Cela rend l'expérience du développeur tellement plus agréable. 🧙‍♂️

Cet article est écrit pour les personnes qui connaissent déjà TypeScript. Je souhaite partager 10 astuces rapides que j'ai apprises tout au long de mon parcours de développeur. 😉

1. Utilisez le type inconnu avant de choisir par défaut Any

Nous savons tous que l'utilisation du anymot-clé est en quelque sorte diabolique. 😈

Heureusement, TypeScript 3.0 a introduit un nouveau mot-clé appelé unknown.

La principale différence entre anyet unknownest que le unknowntype ne peut être attribué qu'au anytype et au unknowntype lui-même. Ainsi, c'est un type beaucoup moins permissif et un excellent substitut à any, car il rappellera constamment à votre éditeur que vous devez le remplacer par quelque chose de plus explicite. En passant de anyà unknown, on n'autorise (presque) rien au lieu de tout autoriser.

Voici un exemple rapide pour illustrer ce que je veux dire :

let  unknownValue: unknown;
let  anyValue: any;

let  unknownValue2: unknown = unknownValue; // This is fine
let  anyValue2: any = unknownValue; // This is fine

let  booleanValue: boolean = unknownValue; // Type 'unknown' is not assignable to type 'boolean'.
let  booleanValue2: boolean = anyValue; // While this works

let  numberValue: number = unknownValue; // Type 'unknown' is not assignable to type 'number'.
let  numberValue2: number = anyValue; // While this works

let  stringValue: string = unknownValue; // Type 'unknown' is not assignable to type 'string'.
let  stringValue2: string = anyValue; // While this works

let  objectValue: object = unknownValue; // Type 'unknown' is not assignable to type 'object'.
let  objectValue2: object = anyValue; // While this works

let  arrayValue: any[] = unknownValue; // Type 'unknown' is not assignable to type 'any[]'.
let  arrayValue2: any[] = anyValue; // While this works

let  functionValue: Function = unknownValue; // Type 'unknown' is not assignable to type 'Function'.
let  functionValue2: Function = anyValue; // While this works

Une autre chose que j'aime faire dans mes projets est d'activer noImplicitAny. Cet indicateur indiquera à TypeScript d'émettre une erreur chaque fois que quelque chose a le type any(défini par vous ou déduit par TypeScript). Plus de détails dans la documentation officielle .

2. Le type Jamais peut être pratique pour la gestion des erreurs

Il existe également un autre type que nous n'utilisons jamais lorsque nous commençons à jouer avec TypeScript : le mot- neverclé. En un mot, il représente le type de valeurs qui ne se produisent jamais.

Il y a quelque temps, j'ai trouvé que ce mot-clé peut être pratique lors de l'écriture de fonctions qui déclenchent une ou plusieurs erreurs et ne retournent jamais rien.

function  throwErrors(statusCode: number): never {
if (statusCode >= 400 && statusCode <= 499) {
throw  Error("Request Error");
}

throw  Error("Something wrong happened.");
}

Nous pouvons également utiliser ce type à notre avantage en nous assurant que chaque situation critique est gérée dans nos fonctions. Voici un exemple rapide de cas où nous avons oublié de tester le cas pour l'espèce humaine.

interface  Dwarf {
weapon: "axe";
}

interface  Elf {
weapon: "bow";
}

interface  Man {
weapon: "sword";
}

type  Specy = Dwarf | Elf | Man;

function  whatIsThatGandalf(specy: Specy) {
let  _ensureAllCasesAreHandled: never;

if (specy.weapon === "axe") {
return  "This is a dwarf";
} else  if (specy.weapon === "bow") {
return  "This is an elf";
}

// ERROR: Type 'Man' is not assignable to type 'never'
_ensureAllCasesAreHandled = specy;
}

3. Interfaces vs Types

Nous entendons souvent cette question de la part de personnes qui viennent de commencer leur parcours TypeScript : quelle est la différence entre une interface et un type ? Dois-je utiliser les deux ? 🤔

Il m'a fallu quelques semaines, au début, pour me fixer une règle car on peut souvent faire la même chose avec les deux. Voici comment je résumerais : Quand je travaille avec des classes ou des objets, j'utilise une interface. Quand je ne le suis pas, j'utilise un type. Cela aiderait si vous vous souveniez que la chose la plus importante est d'être cohérent avec vos choix dans votre base de code.

Bien sûr, il existe aussi quelques différences subtiles entre les deux, comme expliqué dans cette superbe vidéo . Par exemple, une interface peut étendre d'autres interfaces, alors que vous avez besoin d'une union ou d'une intersection pour fusionner deux types ensemble (car ils sont statiques).

De plus, d'après mon expérience, lorsque je traite des types, le message d'erreur peut généralement être plus brutal pour comprendre quand quelque chose ne va pas.

Une autre chose à garder à l'esprit est que la documentation TypeScript vous encourage à utiliser une interface lorsque cela est possible, surtout si vous écrivez une bibliothèque qui exporte un type. La raison en est qu'une interface peut être étendue pour répondre aux besoins de l'application qui utilise votre code.

4. Apprenez à utiliser les types génériques

Les types génériques sont pratiques. Plus vous vous familiarisez avec TypeScript, plus vous les utilisez. Ils permettent à votre code d'être plus flexible en vous permettant de définir vous-même le type. Un exemple peindra mille mots. 😃

Disons que nous voulons geler ou transformer toutes les propriétés d'un objet en propriétés en lecture seule. Eh bien… nous pourrions faire quelque chose comme ça.

interface  Elf {
name: string;
weapon: "bow";
}

const  myElf: Elf = {
name:  "Legolas",
weapon:  "bow",
};

const  freezedElf = Object.freeze(myElf);

// ERROR: Cannot assign to 'name' because it is a read-only property.
freezedElf.name = "Galadriel";

Maintenant, utilisons un type générique pour faire la même chose.

interface  Elf {
name: string;
weapon: "bow";
}

const  myElf: Elf = {
name:  "Legolas",
weapon:  "bow",
};

type  Freeze<T> = {
readonly [P  in  keyof  T]: T[P];
};

const  freezedElf: Freeze<Elf> = myElf;

// ERROR: Cannot assign to 'name' because it is a read-only property.
freezedElf.name = "Galadriel";

// For your information, the generic type Freeze already exists in TypeScript and is called Readonly.

// https://www.typescriptlang.org/docs/handbook/utility-types.html

// So both are equivalent
const  freezedElf: Freeze<Elf> = myElf;
const  freezedElf: Readonly<Elf> = myElf;

Si vous vous posez la question, l' keyofopérateur prend un type d'objet et produit une chaîne ou une union numérique littérale de clés de liste.

Comme vous pouvez le voir dans l'exemple ci-dessus, ce qui est remarquable, c'est que peu importe la forme de l'objet, nous pouvons créer un autre type ( Freeze<Elf>) qui inclura toutes les propriétés définies en lecture seule.

Voici un autre type générique qui définira toutes les propriétés de l'objet comme non en lecture seule.

type  Writable<T> = {
-readonly [P  in  keyof  T]: T[P];
};

Un dernier exemple ici est une fonction utilisant un type générique qui renvoie le dernier élément d'un tableau.

const  getLastElement = <T>(array: T[]) => {
return  array[array.length - 1];
};

5. Le type d'utilitaire partiel pourrait être votre nouveau meilleur ami

Que se passe-t-il si nous souhaitons créer un nouveau type basé sur un autre type mais avec toutes ses propriétés définies sur facultatives. Comment pourrions-nous faire cela ? 🤔

TypeScript est livré avec un utilitaire que j'utilise chaque semaine appelé Partial<Type>. Voici comment cela fonctionne.

interface  Elf {
name: string;
weapon: "bow";
lifepoints: number;
}

type  PartialElf = Partial<Elf>;

// We can omit the weapon attribute as all properties are now optional

const  partialElf: PartialElf = {
name:  "Legolas",
lifepoints:  100,
};

// This is how it is coded behind the curtain
type  Partial<T> = {
[P  in  keyof  T]?: T[P];
};

Génial, non ? Plongeons maintenant dans d'autres types d'utilitaires que vous aimerez utiliser dans votre projet. 😃

6. Autres types d'utilitaires à connaître

Vous avez appris Partial<Type>à construire un type avec toutes les propriétés de Typela valeur facultative. Mais il y en a plus. Voici ceux que j'utilise souvent :

  • Required<Type>: construit un type composé de toutes les propriétés de Typeset to required. Comme vous pouvez le deviner, c'est l'opposé de Partial.
interface  Properties {
a?: number;
b?: string;
}

const  object: Properties = { a:  5 };

// ERROR: Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Properties>'.
const  object2: Required<Properties> = { a:  5 };
  • Readonly<Type>: construit un type avec toutes les propriétés de Typeset en lecture seule, ce qui signifie que les propriétés du type construit ne peuvent pas être réaffectées.
interface  Todo {
title: string;
}

const  todo: Readonly<Todo> = {
title:  "Learn Kendo UI",
};

// ERROR: Cannot assign to 'title' because it is a read-only property.
todo.title = "Hello";
  • Pick<Type, Keys>: construit un type en sélectionnant l'ensemble de propriétés Keys(littéral de chaîne ou union de littéraux de chaîne) dans Type.
interface  Todo {
title: string;
description: string;
completed: boolean;
}

type  TodoPreview = Pick<Todo, "title" | "completed">;

const  todo: TodoPreview = {
title:  "Learn DevCraft",
completed:  false,
};
  • Omit<Type, Keys>: construit un type en sélectionnant toutes les propriétés Typepuis en les supprimant Keys(littéral de chaîne ou union de littéraux de chaîne).
interface  Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}

type  TodoPreview = Omit<Todo, "description">;

const  todo: TodoPreview = {
title:  "Learn Kendo UI",
completed:  true,
createdAt:  1615277055442,
};
  • NonNullable<Type>: Construit un type en excluant nullet undefinedà partir de Type.
// T will be equivalent to string | number
type  T = NonNullable<string | number | undefined | null>;

Pour parcourir la liste complète des types d'utilitaires disponibles dans le monde, rendez -vous sur la documentation officielle .

7. Utilisez des gardes de type pour accéder à une propriété en toute sécurité

Le code à l'épreuve des balles utilise beaucoup les gardes de type. TypeScript permet de savoir plus facilement quand nous devons en utiliser un. 😍

Pour résumer, les gardes de type permettent de vérifier si un objet appartient au bon type. C'est une protection que nous utilisons dans notre code pour nous assurer que rien de mal ne se produit. Ce qui est excellent avec TypeScript, c'est que, avec les erreurs affichées directement dans l'éditeur, on peut deviner quand ajouter des gardes de type.

Voici quelques protections de type standard que vous pouvez utiliser.

  • typeof: L' typeofopérateur renvoie une chaîne indiquant le type de l'opérande non évalué.
function  stringOrNumber(x: number | string) {
if (typeof  x === "string") {
return  "I am a string";
}

return  "I am a number";
}
  • instanceof: L' instanceofopérateur teste pour voir si la propriété prototype d'un constructeur apparaît n'importe où dans la chaîne de prototypes d'un objet. La valeur de retour est une valeur booléenne.
class  Dwarf {
weapon = "axe";
}

class  Elf {
weapon = "bow";
}

function  dwarfOrElf(specy: Dwarf | Elf) {
if (specy  instanceof  Dwarf) {
return  "I am a dwarf";
}

return  "I am an elf";
}
  • in: L' inopérateur renvoie true si la propriété spécifiée se trouve dans l'objet spécifié ou sa chaîne de prototypes.
interface  Dwarf {
weapon: "axe";
lifepoints: number;
}

interface  Elf {
weapon: "bow";
}

function  dwarfOrElf(specy: Dwarf | Elf) {
if ("lifepoints"  in  specy) {
return  "I am a dwarf";
}

return  "I am an elf";
}
  • Protections de type définies par l'utilisateur.
interface  Dwarf {
weapon: "axe";
lifepoints: number;
}

interface  Elf {
weapon: "bow";
}

function  isDwarf(specy: any): specy  is  Dwarf {
return  specy.lifepoints !== undefined;
}

function  dwarfOrElf(specy: Dwarf | Elf) {
if (isDwarf(specy)) {
return  "I am a dwarf";
}

return  "I am an elf";
}

8. Les décorateurs personnalisés peuvent rendre votre code plus facile à lire (l'exemple de la fonction de synchronisation)

J'aime quand j'utilise un cadre ou une bibliothèque qui fait bon usage des décorateurs. Alors que certaines personnes pensent qu'elles sont un anti-modèle et qu'elles ne devraient pas être utilisées, la réalité est un peu plus complexe. Ils peuvent souvent rendre le code plus facile à lire et plus rapide à écrire. Les frameworks comme AdonisJS, NestJS ou encore Angular font beaucoup appel aux décorateurs.

Les décorateurs peuvent être appliqués aux définitions de classe, aux propriétés, aux méthodes, aux accesseurs et aux paramètres. Ils représentent des fonctions qui modifieront le comportement de votre code.

Ils sont faciles à écrire. Voici comment nous pouvons créer un décorateur qui calculera le temps d'exécution d'une fonction.

function  time(name: string) {
return  function (target, propertyKey: string, descriptor: PropertyDescriptor) {
const  fn = descriptor.value;

descriptor.value = (...args) => {
console.time(name);
const  v = fn(...args);
console.timeEnd(name);
return  v;
};
};
}

class  Specy {
@time("attack")
attack() {
// ...
}
}

Vous pouvez avoir un avertissement dans votre éditeur car la prise en charge des décorateurs expérimentaux est une fonctionnalité susceptible de changer dans une future version. Définissez l'option "experimentalDecorators" dans votre tsconfigou jsconfigpour supprimer cet avertissement.

Si vous voulez en savoir plus sur les décorateurs, vous devriez regarder cette superbe vidéo de Fireship (qui est aussi une excellente chaîne de codage à laquelle vous devriez vous abonner 😃).

Un mot d'avertissement : les classes héritées recevront les fonctionnalités du décorateur.

9. Utilisez strictNullChecks et noUncheckedIndexAccess

Il y a deux drapeaux que j'active habituellement dans mon fichier de configuration TypeScript : strictNullCheckset noUncheckedIndexAccess.

  • strictNullChecks: Par défaut, nullet undefinedsont assignables à tous les types dans TypeScript. Avec ce drapeau activé, ils ne le seront pas.
let  foo = undefined;

foo = null; // Will trigger an error

let  foo2: number = 123;

foo2 = null; // Will trigger an error
foo2 = undefined; // Will trigger an error
  • noUncheckedIndexAccess: TypeScript possède une fonctionnalité appelée signatures d'index. Ces signatures sont un moyen de signaler au système de type que les utilisateurs peuvent accéder à des propriétés nommées arbitrairement. Avec ce drapeau activé, ils ne pourront pas le faire.
const  nums = [0, 1, 2];
const  example: number = nums[4]; // WIll trigger an error

10. Utilisez noImplicitOverride (en particulier pour les fonctions fictives)

C'est probablement le conseil le plus utile de cette liste pour les personnes qui écrivent beaucoup de tests.

je vais m'expliquer. Lorsque nous créons des fonctions et des classes moqueuses pour vérifier que notre code se comporte correctement, nous ne voulons pas que les gens renomment une fonction à l'intérieur de cette classe initiale sans être avertis qu'ils doivent également la modifier à l'intérieur de la classe moqueuse. Eh bien… TypeScript vous aidera avec cela.

La première chose à faire pour résoudre ce problème est d'activer noImplicitOverridedans votre fichier de configuration TypeScript et d'utiliser le mot- overrideclé.

class  Specy {
lifepoints = 10;

heal(lifepoints: number) {
this.lifepoints += lifepoints || 10;
}
}

class  MockSpecy  extends  Specy {
override  heal(lifepoints) {
console.log("Let's override the heal method");
}
}

Si quelqu'un modifie la healfonction dans healingla Specyclasse, TypeScript affichera une erreur dans la MockSpecyclasse pour nous dire que nous devons également mettre à jour la méthode ici.

Emballer

Tu l'as fait! Voici dix conseils rapides sur TypeScript que je voulais partager avec vous. 😇

Un dernier conseil est que si vous souhaitez approfondir vos connaissances sur ce magnifique langage, vous devez choisir un framework basé sur celui-ci et plonger dans sa base de code, quelque chose comme Nest, Adonis ou Vue 3. Plus vous lisez le code TS, plus plus vous découvrirez de grandes choses que vous pouvez faire avec.

Lien : https://www.telerik.com/blogs/10-quick-tips-learned-using-typescript

#typescript #javascript

Lokesh Kumar

1603438098

Top 10 Trending Technologies Must Learn in 2021 | igmGuru

Technology has taken a place of more productiveness and give the best to the world. In the current situation, everything is done through the technical process, you don’t have to bother about doing task, everything will be done automatically.This is an article which has some important technologies which are new in the market are explained according to the career preferences. So let’s have a look into the top trending technologies followed in 2021 and its impression in the coming future in the world.

  1. Data Science
    First in the list of newest technologies is surprisingly Data Science. Data Science is the automation that helps to be reasonable for complicated data. The data is produces in a very large amount every day by several companies which comprise sales data, customer profile information, server data, business data, and financial structures. Almost all of the data which is in the form of big data is very indeterminate. The character of a data scientist is to convert the indeterminate datasets into determinate datasets. Then these structured data will examine to recognize trends and patterns. These trends and patterns are beneficial to understand the company’s business performance, customer retention, and how they can be enhanced.

  2. DevOps
    Next one is DevOps, This technology is a mixture of two different things and they are development (Dev) and operations (Ops). This process and technology provide value to their customers in a continuous manner. This technology plays an important role in different aspects and they can be- IT operations, development, security, quality, and engineering to synchronize and cooperate to develop the best and more definitive products. By embracing a culture of DevOps with creative tools and techniques, because through that company will gain the capacity to preferable comeback to consumer requirement, expand the confidence in the request they construct, and accomplish business goals faster. This makes DevOps come into the top 10 trending technologies.

  3. Machine learning
    Next one is Machine learning which is constantly established in all the categories of companies or industries, generating a high command for skilled professionals. The machine learning retailing business is looking forward to enlarging to $8.81 billion by 2022. Machine learning practices is basically use for data mining, data analytics, and pattern recognition. In today’s scenario, Machine learning has its own reputed place in the industry. This makes machine learning come into the top 10 trending technologies. Get the best machine learning course and make yourself future-ready.

To want to know more click on Top 10 Trending Technologies in 2021

You may also read more blogs mentioned below

How to Become a Salesforce Developer

Python VS R Programming

The Scope of Hadoop and Big Data in 2021

#top trending technologies #top 10 trending technologies #top 10 trending technologies in 2021 #top trending technologies in 2021 #top 5 trending technologies in 2021 #top 5 trending technologies

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

Mery tris

Mery tris

1624388400

10 COINS TO $10 MILLION! Top coins to GET RICH in April 2021. DO NOT MISS!!!

0:00 Intro
0:15 Patreon
0:43 Coin #10
2:03 Coin #9
3:33 Coin #8
5:20 Coin #7
6:14 Coin #6
7:49 Coin #5
9:19 Coin #4
11:22 Coin #3
12:19 Coin #2
14:51 Coin #1
16:17 Join The Patreon!

📺 The video in this post was made by K Crypto
The origin of the article: https://www.youtube.com/watch?v=u0Cm8KqjDU4
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#bitcoin #blockchain #10 coins to $10 million #top coins #rich #10 coins to $10 million! top coins to get rich in april 2021

Connor Mills

Connor Mills

1670560264

Understanding Arrays in Python

Learn how to use Python arrays. Create arrays in Python using the array module. You'll see how to define them and the different methods commonly used for performing operations on them.
 

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!


What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  1. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  1. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.


import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:


import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Original article source at https://www.freecodecamp.org

#python