Skip to content

Commit 245fcc1

Browse files
author
mk360
committed
progress in conditional types
1 parent 47602e3 commit 245fcc1

1 file changed

Lines changed: 34 additions & 34 deletions

File tree

docs/documentation/fr/handbook-v2/Type Manipulation/Conditional Types.md

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,14 @@ Quand le type à gauche d'`extends` peut être assigné au type de droite, le r
4141
Ces exemples ne montrent pas forcément l'intérêt des conditions, vu qu'on peut voir si `Dog extends Animal` et décider entre `number` et `string` de nous-même.
4242
Cet intérêt se manifeste surtout en utilisant les types génériques.
4343

44-
For example, let's take the following `createLabel` function:
44+
Considérons cette fonction `createLabel` :
4545

4646
```ts twoslash
4747
interface IdLabel {
48-
id: number /* some fields */;
48+
id: number /* + d'autres champs */;
4949
}
5050
interface NameLabel {
51-
name: string /* other fields */;
51+
name: string /* + d'autres champs */;
5252
}
5353

5454
function createLabel(id: number): IdLabel;
@@ -59,34 +59,34 @@ function createLabel(nameOrId: string | number): IdLabel | NameLabel {
5959
}
6060
```
6161

62-
These overloads for createLabel describe a single JavaScript function that makes a choice based on the types of its inputs. Note a few things:
62+
Ces surcharges de createLabel décrivent une seule fonction JavaScript qui fait des choix en fonction du type de son entrée. Notez, cependant, quelques problèmes :
6363

64-
1. If a library has to make the same sort of choice over and over throughout its API, this becomes cumbersome.
65-
2. We have to create three overloads: one for each case when we're _sure_ of the type (one for `string` and one for `number`), and one for the most general case (taking a `string | number`). For every new type `createLabel` can handle, the number of overloads grows exponentially.
64+
1. Si une librairie doit faire à chaque fois plusieurs choix à travers son API, toutes ces surcharges peuvent vite polluer le code.
65+
2. Trois surcharges doivent être créées : une pour chaque cas où vous êtes _sûrs et certains_ du type de votre valeur (un cas pour `string`, un pour `number`), et une surcharge plus générale (`string | number`). Pour chaque nouveau type que `createLabel` peut gérer, le nombre de surcharges croît exponentiellement.
6666

67-
Instead, we can encode that logic in a conditional type:
67+
À la place, nous pouvons décrire cette logique avec un type conditionnel :
6868

6969
```ts twoslash
7070
interface IdLabel {
71-
id: number /* some fields */;
71+
id: number /* + d'autres champs */;
7272
}
7373
interface NameLabel {
74-
name: string /* other fields */;
74+
name: string /* + d'autres champs */;
7575
}
7676
// ---cut---
7777
type NameOrId<T extends number | string> = T extends number
7878
? IdLabel
7979
: NameLabel;
8080
```
8181

82-
We can then use that conditional type to simplify our overloads down to a single function with no overloads.
82+
Nous pouvons ensuite utiliser les types conditionnels pour éliminer les surcharges et simplifier la signature de la fonction.
8383

8484
```ts twoslash
8585
interface IdLabel {
86-
id: number /* some fields */;
86+
id: number /* + d'autres champs */;
8787
}
8888
interface NameLabel {
89-
name: string /* other fields */;
89+
name: string /* + d'autres champs */;
9090
}
9191
type NameOrId<T extends number | string> = T extends number
9292
? IdLabel
@@ -102,24 +102,24 @@ let a = createLabel("typescript");
102102
let b = createLabel(2.8);
103103
// ^?
104104

105-
let c = createLabel(Math.random() ? "hello" : 42);
105+
let c = createLabel(Math.random() ? "bonjour" : 42);
106106
// ^?
107107
```
108108

109-
### Conditional Type Constraints
109+
### Contraintes de Types Conditionnels
110110

111-
Often, the checks in a conditional type will provide us with some new information.
112-
Just like with narrowing with type guards can give us a more specific type, the true branch of a conditional type will further constrain generics by the type we check against.
111+
Les vérifications sur des types conditionnels vont souvent révéler de nouvelles informations.
112+
Tout comme rétrécir avec des gardes de types peut donner un type plus spécifique, la branche "vrai" du type conditionnel va restreindre le type générique qu'on vérifie avec la contrainte demandée.
113113

114-
For example, let's take the following:
114+
Prenons cet exemple :
115115

116116
```ts twoslash
117117
// @errors: 2536
118118
type MessageOf<T> = T["message"];
119119
```
120120

121-
In this example, TypeScript errors because `T` isn't known to have a property called `message`.
122-
We could constrain `T`, and TypeScript would no longer complain:
121+
TypeScript signale une erreur parce que `T` n'aura pas forcément une propriété `message`.
122+
Il serait possible de contraindre `T`, et TypeScript ne donnera plus d'erreur :
123123

124124
```ts twoslash
125125
type MessageOf<T extends { message: unknown }> = T["message"];
@@ -132,8 +132,8 @@ type EmailMessageContents = MessageOf<Email>;
132132
// ^?
133133
```
134134

135-
However, what if we wanted `MessageOf` to take any type, and default to something like `never` if a `message` property isn't available?
136-
We can do this by moving the constraint out and introducing a conditional type:
135+
Mais si on voulait que `MessageOf` prenne tout, mais soit égal à `never` s'il n'y a pas de propriété `message` ?
136+
Nous pouvons déplacer la contrainte et introduire un type conditionnel :
137137

138138
```ts twoslash
139139
type MessageOf<T> = T extends { message: unknown } ? T["message"] : never;
@@ -153,39 +153,39 @@ type DogMessageContents = MessageOf<Dog>;
153153
// ^?
154154
```
155155

156-
Within the true branch, TypeScript knows that `T` _will_ have a `message` property.
156+
Dans la branche "vrai", TypeScript sait que `T` _va_ avoir une propriété `message`.
157157

158-
As another example, we could also write a type called `Flatten` that flattens array types to their element types, but leaves them alone otherwise:
158+
Dans un tout autre exemple, nous pouvons aussi écrire un type `Flatten` qui aplatit les tableaux en récupérant les types de leurs contenus, mais laisse les types tels quels sinon :
159159

160160
```ts twoslash
161161
type Flatten<T> = T extends any[] ? T[number] : T;
162162

163-
// Extracts out the element type.
163+
// Extraction du type des éléments de tableau
164164
type Str = Flatten<string[]>;
165165
// ^?
166166

167-
// Leaves the type alone.
167+
// Laisse le type tranquille.
168168
type Num = Flatten<number>;
169169
// ^?
170170
```
171171

172-
When `Flatten` is given an array type, it uses an indexed access with `number` to fetch out `string[]`'s element type.
173-
Otherwise, it just returns the type it was given.
172+
Quand `Flatten` reçoit un type tableau, il utilise un accès indexé avec `number` pour récupérer le type des éléments de `string[]`.
173+
Sinon, il retourne simplement le type qui lui a été donné.
174174

175-
### Inferring Within Conditional Types
175+
### Inférence dans les Types Conditionnels
176176

177-
We just found ourselves using conditional types to apply constraints and then extract out types.
178-
This ends up being such a common operation that conditional types make it easier.
177+
Nous avons utilisé des types conditionnels pour appliquer des contraintes et extraire des types.
178+
Cette opération devient très facile avec ces types, qu'elle est devenue très commune.
179179

180-
Conditional types provide us with a way to infer from types we compare against in the true branch using the `infer` keyword.
181-
For example, we could have inferred the element type in `Flatten` instead of fetching it out "manually" with an indexed access type:
180+
Les types conditionnels fournissent une façon d'inférer depuis les types qu'on compare avec le mot-clé `infer`.
181+
Par exemple, on pouvait inférer le type d'éléments de tableaux dans `Flatten` au lieu de le récupérer "manuellement" :
182182

183183
```ts twoslash
184184
type Flatten<Type> = Type extends Array<infer Item> ? Item : Type;
185185
```
186186

187-
Here, we used the `infer` keyword to declaratively introduce a new generic type variable named `Item` instead of specifying how to retrieve the element type of `T` within the true branch.
188-
This frees us from having to think about how to dig through and probing apart the structure of the types we're interested in.
187+
Ici, le mot-clé `infer` introduit un nouveau type générique variable appelé `Item`, au lieu de préciser comment récupérer le type élément de `T` dans la branche vrai.
188+
Cela nous libère de devoir penser à la façon de creuser et obtenir manuellement les types qui nous intéressent.
189189

190190
We can write some useful helper type aliases using the `infer` keyword.
191191
For example, for simple cases, we can extract the return type out from function types:

0 commit comments

Comments
 (0)