1661784423
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. 😉
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 .
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;
}
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.
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];
};
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. 😃
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 :
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 };
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";
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Learn DevCraft",
completed: false,
};
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,
};
// 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 .
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.
function stringOrNumber(x: number | string) {
if (typeof x === "string") {
return "I am a string";
}
return "I am a number";
}
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";
}
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";
}
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";
}
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.
Il y a deux drapeaux que j'active habituellement dans mon fichier de configuration TypeScript : strictNullCheckset noUncheckedIndexAccess.
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
const nums = [0, 1, 2];
const example: number = nums[4]; // WIll trigger an error
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.
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
1661784423
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. 😉
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 .
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;
}
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.
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];
};
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. 😃
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 :
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 };
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";
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Learn DevCraft",
completed: false,
};
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,
};
// 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 .
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.
function stringOrNumber(x: number | string) {
if (typeof x === "string") {
return "I am a string";
}
return "I am a number";
}
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";
}
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";
}
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";
}
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.
Il y a deux drapeaux que j'active habituellement dans mon fichier de configuration TypeScript : strictNullCheckset noUncheckedIndexAccess.
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
const nums = [0, 1, 2];
const example: number = nums[4]; // WIll trigger an error
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.
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
1603438098
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.
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.
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.
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
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
1654588030
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 🌹
If you are here to read the book online get started.
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.
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.
All the amazing contributors 🌹
Share URL: https://basarat.gitbook.io/typescript/
Author: Basarat
Source Code: https://github.com/basarat/typescript-book/
License: View license
1624388400
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
1670560264
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.
Let's get started!
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.
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.
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.
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
:
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()
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()
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()
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.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.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:
TYPECODE | C TYPE | PYTHON TYPE | SIZE |
---|---|---|---|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | wchar_t | Unicode character | 2 |
'h' | signed short | int | 2 |
'H' | unsigned short | int | 2 |
'i' | signed int | int | 2 |
'I' | unsigned int | int | 2 |
'l' | signed long | int | 4 |
'L' | unsigned long | int | 4 |
'q' | signed long long | int | 8 |
'Q' | unsigned long long | int | 8 |
'f' | float | float | 4 |
'd' | double | float | 8 |
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:
import array as arr
.numbers
array.arr.array()
because of import array as arr
.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.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.
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
.
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
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
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
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])
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.
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])
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])
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])
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