Skip to content

Commit e679234

Browse files
options api typescript
1 parent 9bf0cb7 commit e679234

File tree

2 files changed

+45
-44
lines changed

2 files changed

+45
-44
lines changed

src/guide/typescript/composition-api.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# TypeScript con il Composition API {#typescript-with-composition-api}
1+
# TypeScript con Composition API {#typescript-with-composition-api}
22

33
> Si presume che tu abbia già letto [Usare Vue con TypeScript](./overview).
44

src/guide/typescript/options-api.md

Lines changed: 44 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
# TypeScript with Options API {#typescript-with-options-api}
1+
# TypeScript con Options API {#typescript-with-options-api}
22

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).
44
55
:::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.
77
:::
88

9-
## Typing Component Props {#typing-component-props}
9+
## Tipizzare le props dei componenti {#typing-component-props}
1010

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`:
1212

1313
```ts
1414
import { defineComponent } from 'vue'
1515

1616
export default defineComponent({
17-
// type inference enabled
17+
// type inference abilitato
1818
props: {
1919
name: String,
2020
id: [Number, String],
2121
msg: { type: String, required: true },
2222
metadata: null
2323
},
2424
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
2929
}
3030
})
3131
```
3232

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.
3434

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`:
3636

3737
```ts
3838
import { defineComponent } from 'vue'
@@ -47,16 +47,16 @@ interface Book {
4747
export default defineComponent({
4848
props: {
4949
book: {
50-
// provide more specific type to `Object`
50+
// fornia,o un tipo più specifico per l'oggetto
5151
type: Object as PropType<Book>,
5252
required: true
5353
},
54-
// can also annotate functions
54+
// funzioni
5555
callback: Function as PropType<(id: number) => void>
5656
},
5757
mounted() {
58-
this.book.title // string
59-
this.book.year // number
58+
this.book.title // stringa
59+
this.book.year // numero
6060

6161
// TS Error: argument of type 'string' is not
6262
// assignable to parameter of type 'number'
@@ -67,7 +67,7 @@ export default defineComponent({
6767

6868
### Caveats {#caveats}
6969

70-
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:
7171

7272
```ts
7373
import { defineComponent } from 'vue'
@@ -82,7 +82,7 @@ export default defineComponent({
8282
props: {
8383
bookA: {
8484
type: Object as PropType<Book>,
85-
// Make sure to use arrow functions if your TypeScript version is less than 4.7
85+
// Assicurati di utilizzare le arrow functions se TypeScript ha una versione minore della 4.7
8686
default: () => ({
8787
title: 'Arrow Function Expression'
8888
}),
@@ -92,19 +92,19 @@ export default defineComponent({
9292
})
9393
```
9494

95-
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).
9696

97-
## Typing Component Emits {#typing-component-emits}
97+
## Tipizzare gli emits dei componenti{#typing-component-emits}
9898

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.
100100

101101
```ts
102102
import { defineComponent } from 'vue'
103103

104104
export default defineComponent({
105105
emits: {
106106
addBook(payload: { bookName: string }) {
107-
// perform runtime validation
107+
// esegue la runtime validation
108108
return payload.bookName.length > 0
109109
}
110110
},
@@ -120,9 +120,9 @@ export default defineComponent({
120120
})
121121
```
122122

123-
## Typing Computed Properties {#typing-computed-properties}
123+
## Tipizzare le Computed Properties {#typing-computed-properties}
124124

125-
A computed property infers its type based on its return value:
125+
Una computed property ottiene il suo tipo basandosi sul suo valore di ritorno:
126126

127127
```ts
128128
import { defineComponent } from 'vue'
@@ -144,7 +144,7 @@ export default defineComponent({
144144
})
145145
```
146146

147-
In some cases, you may want to explicitly annotate the type of a computed property to ensure its implementation is correct:
147+
In alcuni casi, potresti voler annotare esplicitamente il tipo di una computed property per garantire che la sua implementazione sia corretta:
148148

149149
```ts
150150
import { defineComponent } from 'vue'
@@ -156,7 +156,7 @@ export default defineComponent({
156156
}
157157
},
158158
computed: {
159-
// explicitly annotate return type
159+
// mostra esplicitamente il tipo di return
160160
greeting(): string {
161161
return this.message + '!'
162162
},
@@ -174,11 +174,11 @@ export default defineComponent({
174174
})
175175
```
176176

177-
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.
178178

179-
## Typing Event Handlers {#typing-event-handlers}
179+
## Tipizzazione degli Event Handlers {#typing-event-handlers}
180180

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:
182182

183183
```vue
184184
<script lang="ts">
@@ -187,7 +187,7 @@ import { defineComponent } from 'vue'
187187
export default defineComponent({
188188
methods: {
189189
handleChange(event) {
190-
// `event` implicitly has `any` type
190+
// `event` ha in modo implicito il tipo `any`
191191
console.log(event.target.value)
192192
}
193193
}
@@ -199,7 +199,7 @@ export default defineComponent({
199199
</template>
200200
```
201201

202-
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`:
203203

204204
```ts
205205
import { defineComponent } from 'vue'
@@ -215,7 +215,7 @@ export default defineComponent({
215215

216216
## Augmenting Global Properties {#augmenting-global-properties}
217217

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):
219219

220220
```ts
221221
import axios from 'axios'
@@ -228,18 +228,18 @@ declare module 'vue' {
228228
}
229229
```
230230

231-
See also:
231+
Guarda anche:
232232

233233
- [TypeScript unit tests for component type extensions](https://github.com/vuejs/core/blob/main/packages/dts-test/componentTypeExtensions.test-d.tsx)
234234

235-
### Type Augmentation Placement {#type-augmentation-placement}
235+
### Posizione dell'aumento di tipo {#type-augmentation-placement}
236236

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`.
238238

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!
240240

241241
```ts
242-
// Does not work, overwrites the original types.
242+
// Non funge, sovrascrive i tipi originali
243243
declare module 'vue' {
244244
interface ComponentCustomProperties {
245245
$translate: (key: string) => string
@@ -248,7 +248,7 @@ declare module 'vue' {
248248
```
249249

250250
```ts
251-
// Works correctly
251+
// Funziona correttamente
252252
export {}
253253

254254
declare module 'vue' {
@@ -260,7 +260,7 @@ declare module 'vue' {
260260

261261
## Augmenting Custom Options {#augmenting-custom-options}
262262

263-
Some plugins, for example `vue-router`, provide support for custom component options such as `beforeRouteEnter`:
263+
Alcuni plugin, come `vue-router`, forniscono il supporto per opzioni personalizzate per i componenti, come ad esempio `beforeRouteEnter`:
264264

265265
```ts
266266
import { defineComponent } from 'vue'
@@ -272,7 +272,8 @@ export default defineComponent({
272272
})
273273
```
274274

275-
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:
276277

277278
```ts
278279
import { Route } from 'vue-router'
@@ -284,10 +285,10 @@ declare module 'vue' {
284285
}
285286
```
286287

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.
288289

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.
290291

291-
See also:
292+
Guarda anche:
292293

293294
- [TypeScript unit tests for component type extensions](https://github.com/vuejs/core/blob/main/packages/dts-test/componentTypeExtensions.test-d.tsx)

0 commit comments

Comments
 (0)