You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/guide/typescript/options-api.md
+44-43Lines changed: 44 additions & 43 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,38 +1,38 @@
1
-
# TypeScript with Options API {#typescript-with-options-api}
1
+
# TypeScript con Options API {#typescript-with-options-api}
2
2
3
-
> This page assumes you've already read the overview on [Using Vue with TypeScript](./overview).
3
+
> Si presume che tu abbia già letto [Usare Vue con TypeScript](./overview).
4
4
5
5
:::tip
6
-
While Vue does support TypeScript usage with Options API, it is recommended to use Vue with TypeScript via Composition API as it offers simpler, more efficient and more robust type inference.
6
+
Anche se Vue supporta l'uso di TypeScript con Options API, è consigliato utilizzare Vue con TypeScript tramite Composition API poiché offre un'inferenza dei tipi più semplice, efficiente e robusta.
## Tipizzare le props dei componenti {#typing-component-props}
10
10
11
-
Type inference for props in Options API requires wrapping the component with `defineComponent()`. With it, Vue is able to infer the types for the props based on the `props` option, taking additional options such as `required: true`and`default` into account:
11
+
Ottenere dei tipi per le props nell'Options API richiede di avvolgere il componente con `defineComponent()`. In questo modo, Vue è in grado di ottenere i tipi per le props in base all'opzione `props`, tenendo conto di altre opzioni come `required: true`e`default`:
12
12
13
13
```ts
14
14
import { defineComponent } from'vue'
15
15
16
16
exportdefaultdefineComponent({
17
-
// type inference enabled
17
+
// type inference abilitato
18
18
props: {
19
19
name: String,
20
20
id: [Number, String],
21
21
msg: { type: String, required: true },
22
22
metadata: null
23
23
},
24
24
mounted() {
25
-
this.name//type: string | undefined
26
-
this.id//type: number | string | undefined
27
-
this.msg//type: string
28
-
this.metadata//type: any
25
+
this.name//tipo: string | undefined
26
+
this.id//tipo: number | string | undefined
27
+
this.msg//tipo: string
28
+
this.metadata//tipo: any
29
29
}
30
30
})
31
31
```
32
32
33
-
However, the runtime `props`options only support using constructor functions as a prop's type - there is no way to specify complex types such as objects with nested properties or function call signatures.
33
+
Tuttavia, le opzioni di `props`al runtime supportano solo l'uso di funzioni costruttori come tipo di prop - non c'è modo di specificare tipi complessi come oggetti con proprietà nidificate o chiamate di funzione.
34
34
35
-
To annotate complex props types, we can use the `PropType` utility type:
35
+
Per annotare tipi di prop complessi, possiamo utilizzare il tipo di utilità `PropType`:
If your TypeScript version is less than `4.7`, you have to be careful when using function values for`validator`and`default`prop options - make sure to use arrow functions:
70
+
Se la versione di TypeScript è inferiore a `4.7`, bisogna fare attenzione quando si utilizzano funzioni per le opzioni`validator`e`default`delle props - assicurarsi di utilizzare le arrow functions:
This prevents TypeScript from having to infer the type of`this`inside these functions, which, unfortunately, can cause the type inference to fail. It was a previous [design limitation](https://github.com/microsoft/TypeScript/issues/38845), and now has been improved in [TypeScript 4.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#improved-function-inference-in-objects-and-methods).
95
+
Questa pratica impedisce a TypeScript di dover inferire il tipo`this`all'interno di queste funzioni, che, sfortunatamente, può causare un fallimento nell'inferenza del tipo. Era un [limite di design](https://github.com/microsoft/TypeScript/issues/38845), ed è stato migliorato in [TypeScript 4.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#improved-function-inference-in-objects-and-methods).
## Tipizzare gli emits dei componenti{#typing-component-emits}
98
98
99
-
We can declare the expected payload type for an emitted event using the object syntax of the `emits` option. Also, all non-declared emitted events will throw a type error when called:
99
+
Possiamo dichiarare il tipo di payload previsto per un evento emesso utilizzando la sintassi oggetto dell'opzione `emits`. Inoltre, tutti gli eventi emessi non dichiarati genereranno un errore di tipo quando vengono chiamati.
Explicit annotations may also be required in some edge cases where TypeScript fails to infer the type of a computed property due to circular inference loops.
177
+
Le annotazioni esplicite possono essere necessarie in alcuni casi limite in cui TypeScript non riesce a inferire il tipo di una proprietà calcolata a causa di cicli di inferenza circolare.
178
178
179
-
## Typing Event Handlers {#typing-event-handlers}
179
+
## Tipizzazione degli Event Handlers {#typing-event-handlers}
180
180
181
-
When dealing with native DOM events, it might be useful to type the argument we pass to the handler correctly. Let's take a look at this example:
181
+
Quando si gestiscono eventi nativi del DOM, può essere utile specificare correttamente il tipo dell'argomento passato all'handler. Vediamo un esempio:
182
182
183
183
```vue
184
184
<script lang="ts">
@@ -187,7 +187,7 @@ import { defineComponent } from 'vue'
Without type annotation, the`event`argument will implicitly have a type of `any`. This will also result in a TS error if `"strict": true`or`"noImplicitAny": true`are used in `tsconfig.json`. It is therefore recommended to explicitly annotate the argument of event handlers. In addition, you may need to use type assertions when accessing the properties of`event`:
202
+
Senza annotazione di tipo, l'argomento`event`avrà implicitamente un tipo `any`. Ciò causerà anche un errore di TS se `"strict": true`o`"noImplicitAny": true`sono impostati nel file `tsconfig.json`. È quindi consigliabile annotare esplicitamente l'argomento degli event handlers. Inoltre, potrebbe essere necessario utilizzare le asserzioni di tipo quando si accedono alle proprietà di`event`:
## Augmenting Global Properties {#augmenting-global-properties}
217
217
218
-
Some plugins install globally available properties to all component instances via [`app.config.globalProperties`](/api/application#app-config-globalproperties). For example, we may install `this.$http`for data-fetching or `this.$translate`for internationalization. To make this play well with TypeScript, Vue exposes a`ComponentCustomProperties`interface designed to be augmented via[TypeScript module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation):
218
+
Alcuni plugin installano proprietà disponibili globalmente su tutte le istanze del componente tramite [`app.config.globalProperties`](/api/application#app-config-globalproperties). Ad esempio, potremmo installare `this.$http`per il recupero dei dati o `this.$translate`per l'internazionalizzazione. Per rendere ciò compatibile con TypeScript, Vue espone un'interfaccia`ComponentCustomProperties`progettata per essere estesa tramite[TypeScript module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation):
219
219
220
220
```ts
221
221
importaxiosfrom'axios'
@@ -228,18 +228,18 @@ declare module 'vue' {
228
228
}
229
229
```
230
230
231
-
See also:
231
+
Guarda anche:
232
232
233
233
-[TypeScript unit tests for component type extensions](https://github.com/vuejs/core/blob/main/packages/dts-test/componentTypeExtensions.test-d.tsx)
234
234
235
-
### Type Augmentation Placement {#type-augmentation-placement}
235
+
### Posizione dell'aumento di tipo {#type-augmentation-placement}
236
236
237
-
We can put this type augmentation in a `.ts` file, or in a project-wide`*.d.ts`file. Either way, make sure it is included in `tsconfig.json`. For library / plugin authors, this file should be specified in the`types` property in `package.json`.
237
+
È possibile inserire questa estensione di tipo in un file `.ts`, o in un file`*.d.ts`a livello di progetto. In entrambi i casi, assicurarsi che sia incluso in `tsconfig.json`. Per gli autori di librerie / plugin, questo file dovrebbe essere specificato nella proprietà`types` in `package.json`.
238
238
239
-
In order to take advantage of module augmentation, you will need to ensure the augmentation is placed in a [TypeScript module](https://www.typescriptlang.org/docs/handbook/modules.html). That is to say, the file needs to contain at least one top-level `import`or`export`, even if it is just `export {}`. If the augmentation is placed outside of a module, it will overwrite the original types rather than augmenting them!
239
+
Per poter sfruttare l'estensione di modulo, è necessario assicurarsi che l'aumento sia posizionato in un [modulo TypeScript](https://www.typescriptlang.org/docs/handbook/modules.html). Questo per dire, il file deve contenere almeno un'istruzione `import`o`export` al livello superiore, anche se è solo `export {}`. Se l'aumento è posizionato al di fuori di un modulo, sovrascriverà i tipi originali invece di estenderli!
Without proper type augmentation, the arguments of this hook will implicitly have `any` type. We can augment the `ComponentCustomOptions` interface to support these custom options:
275
+
276
+
Senza un'estensione di tipo adeguata, gli argomenti di questo hook avranno implicitamente il tipo `any`. Possiamo estendere l'interfaccia `ComponentCustomOptions` per supportare queste opzioni personalizzate:
276
277
277
278
```ts
278
279
import { Route } from'vue-router'
@@ -284,10 +285,10 @@ declare module 'vue' {
284
285
}
285
286
```
286
287
287
-
Now the`beforeRouteEnter`option will be properly typed. Note this is just an example - well-typed libraries like `vue-router`should automatically perform these augmentations in their own type definitions.
288
+
Ora l'opzione`beforeRouteEnter`avrà il tipo corretto. Nota che questo è solo un esempio: librerie ben tipizzate come `vue-router`dovrebbero automaticamente eseguire queste estensioni nelle proprie definizioni di tipo.
288
289
289
-
The placement of this augmentation is subject the [same restrictions](#type-augmentation-placement)as global property augmentations.
290
+
La posizione di questa estensione è soggetta alle [stesse restrizioni](#type-augmentation-placement)delle estensioni di proprietà globali.
290
291
291
-
See also:
292
+
Guarda anche:
292
293
293
294
-[TypeScript unit tests for component type extensions](https://github.com/vuejs/core/blob/main/packages/dts-test/componentTypeExtensions.test-d.tsx)
0 commit comments