You are on page 1of 51
01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don 27 JANVIER 2022 / #TYPESCRIPT Apprenez TypeScript - Le guide ultime du débutant ce Danny Adams TypeScript est devenu de plus en plus populaire au cours des derniéres années, et de nombreux emplois exigent maintenant que les développeurs connaissent TypeScript. Mais ne vous inquiétez pas - si vous connaissez déja JavaScript, vous pourrez rapidement prendre TypeScript. Méme si vous n’avez pas I'intention d’utiliser TypeScript, l'apprendre vous donnera une meilleure compréhension de JavaScript et fera de vous un meilleur développeur. Dans cet article, vous apprendrez : * Qu’est-ce que TypeScript et pourquoi devrais-je l'apprendre ? * Comment configurer un projet avec TypeScript * Tous les principaux concepts TypeScript (types, interfaces, génériques, typographie, etc...) hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 111 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don J dl SgdIETIENL fall UN CUpieur Lypesunipe ror et diicne qui resume cet article en une page. Cela facilite la recherche et la révision rapide des concepts / syntaxe. Union Types Fe ead core Ce Caetoty TypeScript aide-mémoire PDF 5 . Qu’est-ce que TypeScript ? TypeScript est un sur-ensemble de JavaScript, ce qui signifie qu'il fait tout ce que JavaScript fait, mais avec quelques fonctionnalités supplémentaires. La principale raison d’utiliser TypeScript est d’ajouter un typage statique a JavaScript. Le typage statique signifie que le type d'une variable ne peut étre modifié 4 aucun moment d’un programme. Cela peut empécher BEAUCOUP de bugs! hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 251 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don // JavaScript let foo = "hello"; foo = 55; // foo has changed type from a string to a number - no probl // TypeScript let foo = "hello"; foo = 55; // ERROR - foo cannot change fron string to number — EEC} TypeScript ne peut pas étre compris par les navigateurs, il doit donc &tre compilé en JavaScript par le compilateur TypeScript (TSC) - dont nous discuterons bientét. TypeScript en vaut-il la peine ? Pourquoi utiliser TypeScript * Larecherche amontré que TypeScript peut repérer 15% des bogues courants. * Lisibilité - il est plus facile de voir ce que le code est censé faire. Et lorsque vous travaillez en équipe, il est plus facile de voir ce que les autres développeurs avaient l'intention de faire. * Cest populaire - connaitre TypeScript vous permettra de postuler & plus de bons emplois. + Lapprentissage de TypeScript vous donnera une meilleure compréhension et une nouvelle perspective sur JavaScript. hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! sist 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Inconvénients de TypeScript * TypeScript prend plus de temps a écrire que JavaScript, car vous devez spécifier des types, donc pour les petits projets solo, il peut ne pas étre utile de l’utiliser. * TypeScript doit étre compilé, ce qui peut prendre du temps, en particulier dans les grands projets. Mais le temps supplémentaire que vous devez consacrer a l’écriture de code plus précis et a la compilation sera plus qu’économisé par le nombre de bogues en moins que vous aurez dans votre code. Pour de nombreux projets, en particulier les projets de moyenne a grande envergure, TypeScript vous fera gagner beaucoup de temps et de maux de téte. Et si vous connaissez déja JavaScript, TypeScript ne sera pas trop difficile 4 apprendre. C'est un excellent outil 4 avoir dans votre arsenal. Comment configurer un projet TypeScript Installer Node et le compilateur TypeScript Tout d'abord, assurez-vous que Node est installé globalement sur votre machine. Installez ensuite le compilateur TypeScript globalement sur votre ordinateur en exécutant la commande suivante : hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 4651 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Pour vérifier si l’installation est réussie (il renverra le numéro de version en cas de succés) : tse -v Comment faire pour compiler TypeScript Ouvrez votre éditeur de texte et créez un fichier TypeScript (par exemple, index.ts). Ecrivez du JavaScript ou du TypeScript : let sport = ‘football’; let id = 5; Nous pouvons maintenant compiler cela en JavaScript avec la commande suivante: tse index TSC compilera le code en JavaScript et le sortira dans un fichier appelé indexjs: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 551 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Si vous souhaitez spécifier le nom du fichier de sortie : tsc index.ts --outfile file-name.js Si vous souhaitez que TSC compile votre code automatiquement, chaque fois que vous apportez une modification, ajoutez le drapeau «watch »: tse index.ts -w Une chose intéressante 4 propos de TypeScript est qu'il signale les erreurs dans votre éditeur de texte pendant que vous codez, mais il compilera toujours votre code - qu’il y ait des erreurs ou non. Par exemple, les éléments suivants provoquent TypeScript pour signaler immédiatement une erreur : var sport = ‘football’; var id = id = '5'; // Error: Type ‘string’ is not assignable to type ‘number’ Mais si nous essayons de compiler ce code avec, le code sera toujours compilé, malgrél'erreur. tse index C’est une propriété importante de TypeScript : elle suppose que le développeur en sait plus. Méme s'il y a une erreur TypeScript, cela ne vous empéche pas de compiler le code. II vous indique qu’il y a hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 51 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Comment configurer le fichier de configuration ts Le fichier de configuration ts doit se trouver dans le répertoire racine de votre projet. Dans ce fichier, nous pouvons spécifier les fichiers racine, les options du compilateur et la rigueur avec laquelle nous voulons que TypeScript vérifie notre projet. Tout d’abord, créez le fichier de configuration t: tse --init Vous devriez maintenant avoir un fichier a la racine du projet. tsconfig. json Voici quelques options qu’il est bon de connaitre (si vous utilisez un framework frontal avec TypeScript, la plupart si ce genre de choses est pris en charge pour vous): "compilerOptions”: { /* Modules */ "target": "es2016", // Change to "ES2@15" to compile to “rootDir": "./sre", // Where to compile from “outDil -/public", // Where to compile to (usually th /* JavaScript Support */ "allowJs": true, // Allow JavaScript files to be compile "checkJs": true, // Type check JavaScript files and repo 7* Emit */ “sourceMap": true, // Create source map files for emitte "removeComments": true, // Don't emit comments 7 hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 7151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don To compile everything and watch for changes: tse -w Remarque : lorsque des fichiers d’entrée sont spécifiés sur la ligne de commande (par exemple, ), les fichiers sont ignorés. tsc index tsconfig. json Types dans TypeScript Types primis . En JavaScript, une valeur primitive est une donnée qui nest pas un objet et qui n’a pas de méthodes. Il existe 7 types de données primitives : * corde * nombre © Bigint * booléen « indéfini * zéro * symbole Les primitives sont immuables : elles ne peuvent pas étre modifiées. Ilest important de ne pas confondre une primitive elle-méme avec une variable assignée a une valeur primitive. Une nouvelle valeur peut étre réaffectée a la variable, mais la valeur existante ne peut hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! ast soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Voici un exemple : let name = ‘Danny’; name. toLowerCase() ; console.log(name); // Danny - the string method didn't mutate th let arr = [1, 3, 5, 7]; arr.pop(); console.log(arr); // [1, 3, 5] - the array method mutated the ar name = ‘Anna’ // Assignment gives the primitive a new (not a mut ——EEE >» En JavaScript, toutes les valeurs primitives (a l'exception de null et undefined) ont des équivalents d’objet qui s‘enroulent autour des valeurs primitives. Ces objets wrapper sont String, Number, BigInt, Booléen et Symbol. Ces objets wrapper fournissent les méthodes qui permettent de manipuler les valeurs primitives. Pour en revenir 4 TypeScript, nous pouvons définir le type que nous voulons qu’une variable ajoute (appelé « annotation de type » ou « signature de type ») aprés avoir déclaré une variable. Exemples: : type let id: number = 5; let firstname: string = ‘danny’; et hasDog: boolean = true; let unit: unit = 55 runber; // Declare variable without assigning a value hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 951 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don let id = 5; // TS knows it’s a number let firstname = ‘danny’; // TS knows it's a string let hasDog = true; // TS knows it's a boolean hasDog = ‘yes’; // ERROR Nous pouvons également définir une variable pour pouvoir étre de type union. Un type d’u types peuvent étre affectés : n est une variable a laquelle plusieurs let age: string | number; age = 26; age = '26' Types de référence En JavaScript, presque « tout » est un objet. En fait (et de maniére confuse), les chaines, les nombres et les booléens peuvent étre des objets s'ils sont définis avec le mot-clé : new let firstname = new String('Danny'); console.log(firstname); // String {'Danny'} Mais lorsque nous parlons de types de référence en JavaScript, nous faisons référence a des tableaux, des objets et des fonctions. hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 10151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don FOr COU Gur Ure yartians COUUHE 1O2 Ly BES BENE vo HES Ly peo Ue référence, discutons de la différence fondamentale. Siun type primitif est affecté a une variable, nous pouvons considérer cette variable comme contenant la valeur primitive. Chaque valeur primitive est stockée dans un emplacement unique en mémoire. Si nous avons deux variables, x et y, et qu’elles contiennent toutes deux des données primitives, alors elles sont complétement indépendantes l'une de l'autre: X et Y contiennent tous deux des données primitives indépendantes uniques let x = 2; let y = 1; x= Y; y = 100; console.log(x); // 1 (even though y changed to 10, x is still 1 hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don addr: 100 point et point2 contiennent une référence a l'adresse ol l'objet est stocké let pointl = (x: 1, y: 135 let point2 = point; pointi.y = 100; console. log(point2.y); // 1@@ (point1 and point2 refer to the same mem II s'agissait d'un bref apercu des types primaires par rapport aux types de référence. Consultez cet article si vous avez besoin d’une explication plus approfondie: Types | vs types de Arrays in TypeScript In TypeScript, you can define what type of data an array can contain: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 12181 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. let books: object] = [ { name: ‘Fooled by randomness’, author: ‘Nassim Taleb’ }, { name: 'Sapiens', author: ‘Yuval Noah Harari’ }, J3 // can only contain objects let arr: any[] = [‘hello', 1, true]; // any basically reverts TypeScri ids. push(6); ids.push('7'); // ERROR: Argument of type ‘string’ is not assignable t ———— » You can use union types to define arrays containing multiple types: Jet person: (string | number | boolean)[] = ['Danny’, 1, true]; Person[@] = 1003 person[1] = {name: 'Danny'} // Error = person array can't contain obje If you initialise a variable with a value, it's not necessary to explicitly state the type, as TypeScript will infer it: let person = ['Danny’, 1, true]; // This is identical to above example person[@] = 1003 person[1] = { name: ‘Danny’ }; // Error - person array can't contain o » There is a special type of array that can be defined in TypeScript: Tuples. A tuple is an array with fixed size and known datatypes. They are stricter than regular arrays. let person: [string, number, boolean] = ['Danny', 1, true]; hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 13951 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. Objects in TypeScript , Objects in TypeScript must have all the correct properties and value types: // Declare a variable called person with a specific object type annota let person: { name: strings location: string; isProgranmer: boolean; ub // Assign person to an object with all the necessary properties and va person = { name: ‘Danny’, location: ‘UK’, isProgranmer: true, ub person. isProgranmer = ‘Yes’; // ERROR: should be a boolean person = { name: ‘John’, location: ‘us’, : missing the isProgrammer property —— » When defining the signature of an object, you will usually use an interface. This is useful if we need to check that multiple objects have the same specific properties and value types: interface Person { name: strings location: string; hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 14051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don name: "Danny", location: ‘UK’, isProgranmer: true, ub let person2: Person = { name: ‘Sarah, location: ‘Germany’, isProgranmer: false, We can also declare function properties with function signatures. We can do this using old-school common JavaScript functions (), or ES6 arrow functions (): sayHi sayBye interface Speech { sayHi(name: string): strings sayBye: (name: string) => string; + let saystuff: Speech = sayHi: function (name: string) ¢ return “Hi ${name} ; a sayBye: (name: string) => “Bye ${name}”, ub console. log(sayStuff.sayHi(‘Heisenberg")); // Hi Heisenberg console. log(sayStuff.sayBye( ‘Heisenberg’)); // Bye Heisenberg Note that in the object, or could be given an arrow function or a common JavaScript function - TypeScript doesn't care. sayStuff sayHi sayBye Functions in TypeScript hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 15151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. // Define a function called circle that takes a diam variable of type function circle(diam: number): string { + Math.PI * diam; return ‘The circumference is console. log(circle(10)); // The circumference is 31.41592653589793 ——E » The same function, but with an ES6 arrow function: const circle = (diam: number): string => { return ‘The circumference is ' + Math.PI * diam; ub console. log(circle(10)); // The circumference is 31.41592653589793 Notice how it isn't necessary to explicitly state that is a function; TypeScript infers it. TypeScript also infers the return type of the function, so it doesn't need to be stated either. Although, if the function is large, some developers like to explicitly state the return type for clarity. circle // Using explicit typing const circle: Function = (diam: number): string => { return ‘The circumference is ' + Math.PI = diam; // Inferred typing - TypeScript sees that circle is a function that al const circle = (diam: number) => { return ‘The circumference is ' + Math.PI = diam; us —_= >» hitps:wwufreecodecamp.orginewslearr-ypescript beginners-guide! 16151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. Also notice below how 1s a union type that can be a number or string: c const add = (a: number, b: number, ¢?: number | string) => { console. 1og(c); return a + bs ub console. log(add(5, 4, "I could pass a number, string, or nothing here! // I could pass a number, string, or nothing here! 9 —— » A function that returns nothing is said to return void - a complete lack of any value. Below, the return type of void has been explicitly stated. But again, this isn't necessary as TypeScript will infer it. const logMessage = (msg: string): void => { console.log('This is the message: * + msg); us logessage('TypeScript is superb’); // This is the message: TypeScript —— » If we want to declare a function variable, but not define it (say exactly what it does), then use a function signature. Below, the function must follow the signature after the colon: sayHello // Declare the varible sayHello, and give it a function signature that let sayHello: (name: string) => voids hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 1151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don sayHello('Danny’); // Hello Danny e scrim to help you learn | ns in TypeScript: . scrimba Dynamic (any) types Using the type, we can basically revert TypeScript back into JavaScript: any Jet age: any = '100'; age = 100; age = ( years: 100, hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 18151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don It's recommended to avoid using the type as much as you can, as it prevents TypeScript from doing its job - and can lead to bugs. any Type Aliases Type Aliases can reduce code duplication, keeping our code DRY. Below, we can see that the type alias has prevented repetition, and acts as a single source of truth for what data a person object should contain. PersonObject type StringOrNumber string | numbers type PersonObject = { name: string; id: StringOrNumber; % const person: Persondbject name: ‘John’, id: 1, or const person2: Persondbject name: ‘Delia’, id: 2, const sayHello = (person: PersonObject) => { return ‘Hi ' + person.name; ub const sayGoodbye = (person: PersonObject) => return 'Seeya ' + person.name; ub hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 10151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don INI Ulal WHENEVER WE Ly LU dLLESS UUM EIEITIENLS, LYPESUF IPL IS. never sure that they actually exist. The below example shows the problem: const link = document .querySelector('a"); console. log(link.href); // ERROR: Object is possibly ‘null’. TypeScrip — aE » With the non-null assertion operator (!) we can tell the compiler explicitly that an expression has value other than or . This is can be useful when the compiler cannot infer the type with certainty, but we have more information than the compiler. null undefined // Here we are telling TypeScript that we are certain that this anchor const link = document .querySelector(‘a')!5 console. log(link.href); // www. freeCodeCamp.org — > Notice how we didn't have to state the type of the variable. This is because TypeScript can clearly see (via Type Inference) that it is of type. link HTMLAnchorElement But what if we needed to select a DOM element by its class or id? TypeScript can't infer the type, as it could be anything. const form = document. get€lementById( 'signup-form’); hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 20051 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Above, we get two errors. We need to tell TypeScript that we are certain exists, and that we know it is of type . We do this with type casting: form HTMLFormElement const form = document. get€lementById('signup-form') as HTMLFormElement console. log(form.method); // post — |} And TypeScript is happy! TypeScript also has an Event object built in. So, if we add a submit event listener to our form, TypeScript will give us an error if we call any methods that aren't part of the Event object. Check out how cool TypeScript is - it can tell us when we've made a spelling mistake: const form = document ..getElementById('signup-form') as HTMLFormElement form. addEventListener( ‘submit’, (e: Event) => { e.preventDefault(); // prevents the page from refreshing console.1og(e.tarrget); // ERROR: Property ‘tarrget’ does not exist ns Here's an interactive scrim to help you learn more about types in TypeScript: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 21151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Classes in TypeScript We can define the types that each piece of data should be in a class: class Person { name: string; isCool: boolean; pets: nunber; constructor(n: string, ¢: boolean, p: number) { ‘this.name = nj ‘this.isCool = ¢; ‘this. pets sayHello() { return “Hi, my name is ${this.name} and I have ${this.pets} pets’; const person = new Person('Danny', false, 1); const person2 = new Person('Sarah’, ‘yes’, 6); // ERROR: Argument of t hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 22151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. We could then create a array that only includes objects constructed from the class: people Person let People: Person[] = [persont, person2]; We can add access modifiers to the properties of a class. TypeScript also provides a new access modifier called. readonly class Person ¢ readonly name: string; // This property is immutable - it can only b private isCool: boolean; // Can only access or modify fron methods w protected email: string; // Can access or modify from this class and public pets: number; // Can access or modify from anywhere - includi constructor(n: string, ¢: boolean, e: string, p: number) { this.name ‘this.isCool this.email = e; this.pets = ps n5 G sayMyName() { console. 1og("Your not Heisenberg, you're ${this.name}*); const personi = new Person('Danny’, false, ‘dan@e.com’, 1); console. log(personi.name); // Fine Person1.name = ‘James’; // Error: read only console. log(personi.isCool); // Error: private property - only accessi console. log(person1.email); // Error: protected property - only access console. log(personi.pets); // Public property - so no problem —— EE » hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 23151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don class Person { constructor( readonly name: string, private isCool: boolean, protected email: string, public pet: 0 number: sayMyName() { console. log(* Your not Heisenberg, you're ${this.name}); const person = new Person(‘Danny’, false, ‘dan@e.com’, 1); console. log(person1.name); // Danny Writing it the above way, the properties are automatically assigned in the constructor - saving us from having to write them all out. Note that if we omit the access modifier, by default the property will be public. Classes can also be extended, just like in regular JavaScript: class Programmer extends Person { programmingLanguages: string[]; constructor( name: string, isCool: boolean, email: string, number, pets: pl: stringl] 4 // The super call must supply all paraneters for base (Person) cla super(name, isCool, email, pets); hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 24051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don For more on classes, refer to the official TypeScript docs. Here's an interactive scrim to help you learn more about classes in TypeScript: Modules in TypeScript In JavaScript, a module is just a file containing related code. Functionality can be imported and exported between modules, keeping the code well organized. TypeScript also supports modules. The TypeScript files will compile down into multiple JavaScript files. hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 25151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don “target”: "es2016", es2015" “module” : (Although, for Node projects you very likely want - Node doesn't yet support modern importing/exporting.) "module": "CommonJs" Now, in your HTML file, change the script import to be of type module: We can now import and export files using ES6: // src/hello.ts export function sayHi() { console. log( ‘Hello there! '); // src/script.ts import { sayHi } from './hello.js*; sayHi(); // Hello there! Note: always import as a JavaScript file, even in TypeScript files. Interfaces in TypeScript Interfaces define how an object should look: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 26151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don name: string; age: nunber; function sayHi(person: Person) { console. log(*Hi ${person. name} ); } sayHi({ name: ‘John’, age: 48, })5 // Hi John You can also define an object type using a type alias: type Person = { strings numbers name: age: function sayHi(person: Person) { console. log("Hi ${person.nane}” ); sayi(( name: ‘John’, age: 48, 3s // Hi John Or an object type could be defined anonymously: function sayHi(person: { name: strings age: number }) ¢ console. 1og("Hi ${person.name}”); sayHi({ hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 27151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Interfaces are very similar to type aliases, and in many cases you can use either. The key distinction is that type aliases cannot be reopened to add new properties, vs an interface which is always extendable. The following examples are taken from the TypeScript docs. Extending an interface: interface Animal { name: string + interface Bear extends Animal { honey: boolean + const bear: Bear - { name: "Winnie", honey: true, } Extending a type via intersections: type Animal = { name: string type Bear = Animal & honey: boolean const bear: Bear = hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 28151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Adding new fields to an existing interface: interface Animal { name: string } // Re-opening the Animal interface to add a new field interface Animal { tail: boolean const dog: Animal = { name: "Bruce", tail: true, + Here's the key difference: a type cannot be changed after being created: type Animal = { name: string type Animal = { tail: boolean } // ERROR: Duplicate identifier ‘Animal’. Asa rule of thumb, the TypeScript docs recommend using interfaces to define objects, until you need to use the features of a type. Interfaces can also define function signatures: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 20151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don name: string age: number speak(sentence: string): void + const personl: Person = { name: "John", age: 48, speak: sentence => console. 1log(sentence), + You may be wondering why we would use an interface over a class in the above example. One advantage of using an interface is that it is only used by TypeScript, not JavaScript. This means that it won't get compiled and add bloat to your JavaScript. Classes are features of JavaScript, so it would get compiled. Also, a class is essentially an object factory (that is, a blueprint of what an object is supposed to look like and then implemented), whereas an interface is a structure used solely for type-checking. While a class may have initialized properties and methods to help create objects, an interface essentially defines the properties and type an object can have. Interfaces with classes We can tell a class that it must contain certain properties and methods by implementing an interface: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 30051 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don class Person implements HasFormatter { constructor(public username: string, protected password: string) {} format() { return this.username.toLocaleLowerCase(); , + // Must be objects that implement the HasFormatter interface let personi: HasFormatter; let person2: HasFormatter; person = new Person(‘Danny', ‘password123"); person2 = new Person(‘Jane’, 'TypeScripter199@"); console. log(personi.format()); // danny —_— ee > Ensure that is an array of objects that implement (ensures that each person has the format method): people HasFormatter let people: HasFormatter[] = []5 people. push(person1) ; people. push(person2) ; Literal types in TypeScript In addition to the general types and , we can refer to specific strings and numbers in type positions: string number // Union type with a literal type in each position let favouriteColor: ‘red’ | ‘blue’ | ‘green’ | ‘yellow’; hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 31151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Here's an interactive scrim to help you learn more about literal types in TypeScript: Generics Generics allow you to create a component that can work over a variety of types, rather than a single one, which helps to make the component more reusable. Let's go through an example to show you what that means... The function accepts any object, and returns a new object with all the properties and values of the passed in object, plus an property hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 3251 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don const addID = (obj: object) => { let id = Math.floor(Math.random() * 1000); return { Pr bj, id ); Jet person = addID({ name: ‘John’, age: 48 }); console. log(persont.id); // 271 console. log(person1.name); // ERROR: Property ‘name’ does not exist on —— » As you can see, TypeScript gives an error when we try to access the property. This is because when we pass in an object to, we are not specifying what properties this object should have - so TypeScript has no idea what properties the object has (it hasn't "captured" them). So, the only property that TypeScript knows is on the returned object is. name addID id So, how can we pass in any object to, but still tell TypeScript what properties and values the object has? We can use a generic, - where is known as the type parameter: addID T // is just the convention - e.g. we could use or const addID = (obj: T) => { let id = Math. floor(Math.random() * 1800); return { ...0bj, id }; ub What does this do? Well, now when we pass an object into , we have told TypeScript to capture the type - so becomes whatever type we hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 33151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don But, we now have a problem: anything can be passed into and TypeScript will capture the type and report no problem: addID let personi let person2 addID({ name: ‘John’, age: 40 }); addID(*Sally'); // Pass in a string - no problem console. log(persont.id); // 271 console.log(persont.name); // John console. log(person2. id) ; console. log(person2.name); // ERROR: Property ‘name’ does not exist on — » When we passed ina string, TypeScript saw no issue. It only reported an error when we tried to access the property. So, we need aconstraint: we need to tell TypeScript that only objects should be accepted, by making our generic type, , an extension of i name T object const addID = (obj: T) => { let id = Math.floor(Math.random() * 1000); return { ...0bj, id }; ub let personi Jet person2 addID({ name: ‘John', age: 40 }); addID(*Sally'); // ERROR: Argument of type ‘string’ isn ——EEEEEE! » The error is caught straight away - perfect... well, not quite. In JavaScript, arrays are objects, so we can still get away with passing in an array: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 34051 012023 00.09 ‘Apprenez TypeSerip- Le guide utme du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. console.1og(person2.id); // 824 console.1og(person2.name); // Error: Property ‘name’ does not exist on —— » We could solve this by saying that the object argument should have aname property with string value: const addID = (obj: T) => { let id = Math.floor(Math.random() * 1000) ; return { ...0bj, id }5 pr let person2 = addID(['Sally', 26]); // ERROR: argument should have an ——— >» The type can also be passed in to , as below - but this isn't necessary most of the time, as TypeScript will infer it. // Below, we have explicitly stated what type the argument should be b let personi = addiD<{ name: string; age: number }>({ name: ‘John’, age ——EEE » Generics allow you to have type-safety in components where the arguments and return types are unknown ahead of time. In TypeScript, generics are used when we want to describe a correspondence between two values. In the above example, the return type was related to the input type. We used a generic to describe the correspondence. hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 35151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. teens any any function loglength(a: any) { console. log(a.length); // No error return aj Jet hello = ‘Hello world"; Joglength(hello); // 11 let howMany = 8; loglength(howMany); // undefined (but no TypeScript error - surely we — » We could try using a gene! function loglength(a: T) { console. log(a.length); // ERROR: TypeScript isn't certain that return a; + —— >» At least we are now getting some feedback that we can use to tighten up our code. Solution: use a generic that extends an interface that ensures every argument passed in has a length property: interface hasLength { Length: sunbers + function loglength(a: T) ( hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 36051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don let hello = ‘Hello world’ ; logtength(hello); // 11 let howtany = 83 LogLength(howany); // Error: numbers don't have length properties We could also write a function where the argument is an array of elements that all have a length property: interface hasLength { length: numbers + function loglengths(a: T[]) { a.forzach( (element) => { console. log(element . length) ; ys let arr = [ "This string has a length prop’, ['This’, ‘arr’, ‘has, ‘length’ ], { material: ‘plastic’, length: 3@ }, is Joglengths(arr); 1/29 4 11 38 Generics are an awesome feature of TypeScript! Generics with interfaces When we don't know what type a certain value in an object will be ahead of time, we can use a generic to pass in the type: hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 37151 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don interface Person { strings age: number; documents: T; nam // We have to pass in the type of “documents” - an array of strings in const persont: Person = { name: ‘John’, age: 48, documents: ['passport', ‘bank statement’, ‘visa'], ub // Again, we implement the “Person” interface, and pass in the type fo const person2: Person = { name: ‘Delia’, age: 46, documents: ‘passport, P45’, Gb Enums in TypeScript Enums are a special feature that TypeScript brings to JavaScript. Enums allow us to define or declare a collection of related values, that can be numbers or strings, as a set of named constants. enum ResourceType { BOOK, AUTHOR, FILM, DIRECTOR, PERSON, console. log(ResourceType.800K); // @ console. log(ResourceType.AUTHOR); // 1 // To start from 1 hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 38051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don DIRECTOR, PERSON, console. log(ResourceType. 800K); // 1 console. log(ResourceType.AUTHOR); // 2 By default, enums are number based - they store string values as numbers. But they can also be strings: enum Direction { Up = "Up's Right = ‘Right’, Down = ‘Down’, Left "Left', console. log(Direction.Right); // Right console. log(Direction.Down); // Down Enums are useful when we have a set of related constants. For example, instead of using non-descriptive numbers throughout your code, enums make code more readable with descriptive constants. Enums can also prevent bugs, as when you type the name of the enum, intellisense will pop up and give you the list of possible options that can be selected. TypeScript strict mode Itis recommended to have all strict type-checking operations enabled in the file. This will cause TypeScript to report more errors, hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 30051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don // tsconfig.json “strict": true Let's discuss a couple of the things that strict mode does: no implicit any, and strict null checks. No imp! any In the function below, TypeScript has inferred that the parameter is. of type. As you can see, when we pass ina number to this function, and try to log a property, no error is reported. Not good. a any name function LogName(a) { /1 No error? console. log(a.name) ; + LogName(97) ; With the option turned on, TypeScript will instantly flag an error if we don't explicitly state the type of : noImplicitAny a // ERROR: Parameter ‘a’ implicitly has an ‘any’ type. function logName(a) { console. log(a.name) ; + hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 40051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Call du Lo UTTeEXpeLteu EFTUrs at runtime. strictNullChecks null undefined With set to true, and have their own types, and you'll get a type error if you assign them to a variable that expects a concrete value (for example, ). strictNullChecks null undefined string Jet whoSangThi: : string = getSong(); const singles = [ { song: ‘touch of grey’, artist: ‘grateful dead’ }, { sony i “paint it black’, artist: ‘rolling stones’ }, const single = singles.find((s) => s.song whoSangThis) ; console. log(single.artist) ; Above, has no guarantee that it will find the song - but we have written the code as though it always will. singles. find By setting to true, TypeScript will raise an error because we haven't made a guarantee that exists before trying to use it: strictNullChecks single const getSong = () => { return ‘song’; ub et whoSangThis: string = getSong(); const singles = [ : ‘touch of grey’, artist: "grateful dead" }, “paint it black’, artist: ‘rolling stones’ }, hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 41st 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don console.log(single.artist); // ERROR: Object is possibly ‘undefined. TypeScript is basically telling us to ensure exists before using it. We need to check if it isn't or first: single null undefined if (single) { console. log(single.artist); // rolling stones + Narrowing in TypeScript Ina TypeScript program, a variable can move from aless precise type to a more precise type. This process is called type narrowing. Here's a simple example showing how TypeScript narrows down the less specific type of to more specific types when we use if- statements with: string | number typeof function addAnother(val: string | number) { if (typeof val === ‘string’) { // TypeScript treats ‘val’ as a string in this block, so we can us return val.concat(" ' + val); } // TypeScript knows “val” is a number here return val + val; console. log(addAnother(‘woooo')); // Woooo Woooo. console.log(addAnother(20)); // 40 —EEEEEEE >» hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 4251 soi07/2023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. WIKI Call cIer VE UF Lye UI. duavenicies rine rain interface Vehicle ( ‘topSpeed: numbers + interface Train extends Vehicle { carriages: number; interface Plane extends Vehicle { wingspan: nunber; + ‘type PlaneOrTrain = Plane | Train; function getSpeedRatio(v: PlaneOrTrain) { // In here, we want to return topSpeed/carriages, or topSpeed/wingSp console. log(v.carriages); // ERROR: ‘carriages’ doesn't exist on typ Since the function is working with multiple types, we need a way of distinguishing whether is a or . We could do this by giving both types acommon distinguishing property, with a literal string value: getSpeedRatio v Plane Train // All trains must now have a type property equal to ‘Train’ interface Train extends Vehicle { type carriages: number; “Train’; // All trains must now have 2 type property equal to ‘Plane’ interface Plane extends Vehicle { type: ‘Plane’; wingSpan: number; + hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 451 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Now we, and TypeScript, can narrow down the type of: v function getSpeedRatio(v: PlaneOrTrain) { if (vitype === Train’) { // TypeScript now knows that “v" is definitely a ‘Train’. Tt has n return v.topspeed / v.carriages; , // If it's not a Train, TypeScript narrows down that “v" must be a P return v.topSpeed / v.wingSpan; + type: ° carriages: 20, ub console. log(getSpeedRatio(bigTrain)); // 5 < Bonus: TypeScript with React TypeScript has full support for React and JSX. This means we can use TypeScript with the three most common React frameworks: * create-react-app (TS setup) * Gatsby (TS setup) * Next,js (TS setup) If you require a more custom React-TypeScript configuration, you could setup Webpack (a module bundler) and configure the yourself. But most of the time, a framework will do the job. tsconfig. json hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! ais 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant px create-react-app my-app --template typescript # or yarn create react-app my-app --template typescript In the src folder, we can now create files with (for regular TypeScript files) or (for TypeScript with React) extensions and write our components with TypeScript. This will then compile down into JavaScript in the public folder. .ts_.tsx React props with TypeScript Below, we are saying that should be a React functional component that accepts a props object with the props , which should be a string, and, which should be anumber. Person name age // svc/components/Person.tsx import React from ‘react’; const Person: React.FC<{ name: strings age: numbers y> = ({ name, age }) —> { return (
{name}
{age}
: hs export default Person; hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! Faire un don 45051 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don interface Props { name: string; age: nunber; } const Person: React.FC = ({ name, age }) => ( return (
{name}
{age}
5 We can then import this component into . If we don't provide the necessary props, TypeScript will give an error. App. tsx import React from ‘react’; import Person from './components/Person' ; const App: React.FC = () => { return (
vw For more information on React with TypeScript, checkout these awesome React-TypeScript cheatsheets. Useful resources & further reading © The official TypeScript docs ¢ The Net Ninja's TypeScript video series (awesome!) * Ben Awad's TypeScript with React video * Narrowing in TypeScript (a very interesting feature of TS that you should learn) * Function overloads * Primitive values in JavaScript + JavaScript objects Thanks for reading! hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 48151 01072023 00:09 ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don PDF or order a physical poster. For more from me, you can find me on Twitter and YouTube. Cheers! Danny Adams | ama fullstack web developer focused on React, NextJS, TypeScript, Node, and PHP, Currently freelancing fulltime with WordPress. If you read this far, tweet to the author to show them you care. Tweet a thanks Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started ADVERTISEMENT hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! 49151 soi07/2023 00:09 Federal 1ax dentincation Number: 82-U//¥240) ‘Apprenez TypeScript ~ Le guide ume du débutant Faire un don Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world. Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff. You can make a tax-deductible donation here. Bash If Statement Align Text in HTML JS Copy an Object Tableau vs Power Bl ‘What is rem in CSS? Quick Sort Algorithm How to Open XML Files What's Node Used For? Declare an Array in JS Python String Contains Append String in Python What is Data Analytics? Git Revert to Last Commit What is an IDE in Coding? Convert Int to String C++ hitps:wwufreecodecamp.orginewslearr-ypescrptbeginners-quide! Trending Guides CSvsIT JS Append SQL Select PHP Explode PHP Implode What is YAML? What is an ORM? SOLID Principles SQL Date Example JavaScript Minify Data Analyst vs Scientist Lowercase a Python String Stratified Random Sampling Linux Environment Variables Which Programming Language? Our Charity 50151 3010712028 00:08 ‘Apprenez TypeScript ~ Le guide ume du débutant Forum Faire un don Soutenez notre charité et notre mission. Faites un don a freeCodeCamp.org. hitps:iwtreecodecamp.orginewsilearr-ypescrpt-beginners-guide! 51151

You might also like