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
> O [Vue CLI](https://cli.vuejs.org)fornece ferramentas integradas de suporte ao TypeScript.
4
4
5
-
## Official Declaration in NPM Packages
5
+
## Declaração Oficial em Pacotes NPM
6
6
7
-
A static type system can help prevent many potential runtime errors as applications grow, which is why Vue 3 is written in TypeScript. This means you don't need any additional tooling to use TypeScript with Vue - it has a first-class citizen support.
7
+
Um sistema de tipagem estática pode ajudar a prevenir diversos potenciais erros de _runtime_ conforme as aplicações crescem, é por isso que o Vue 3 é escrito em TypeScript. Isso significa que você não precisa de nenhum ferramental adicional para usar TypeScript com Vue - temos um suporte de primeira-classe.
8
8
9
-
## Recommended Configuration
9
+
## Configuração Recomendada
10
10
11
11
```js
12
12
// tsconfig.json
13
13
{
14
14
"compilerOptions": {
15
15
"target":"esnext",
16
16
"module":"esnext",
17
-
//this enables stricter inference for data properties on `this`
17
+
//isso permite uma inferência mais estrita para propriedades de dados no `this`
18
18
"strict":true,
19
19
"jsx":"preserve",
20
20
"moduleResolution":"node"
21
21
}
22
22
}
23
23
```
24
24
25
-
Note that you have to include `strict: true` (or at least`noImplicitThis: true` which is a part of `strict` flag) to leverage type checking of`this`in component methods otherwise it is always treated as `any` type.
25
+
Observe que você precisa incluir `strict: true` (ou ao menos`noImplicitThis: true`, que é uma parte da _flag_`strict`) para aumentar a checagem do`this`em métodos de componentes. Caso contrário, será sempre tratado como tipo `any`.
26
26
27
-
See [TypeScript compiler options docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html)for more details.
27
+
Veja a [documentação das opções do compilador TypeScript](https://www.typescriptlang.org/docs/handbook/compiler-options.html)para mais detalhes.
28
28
29
-
## Development Tooling
29
+
## Ferramentas de Desenvolvimento
30
30
31
-
### Project Creation
31
+
### Criação de Projeto
32
32
33
-
[Vue CLI](https://github.com/vuejs/vue-cli)can generate new projects that use TypeScript. To get started:
33
+
O [Vue CLI](https://github.com/vuejs/vue-cli)pode gerar novos projetos que usam TypeScript. Para começar:
34
34
35
35
```bash
36
-
# 1. Install Vue CLI, if it's not already installed
36
+
# 1. Instale o Vue CLI, se não estiver instalado
37
37
npm install --global @vue/cli
38
38
39
-
# 2. Create a new project, then choose the "Manually select features" option
39
+
# 2. Crie um novo projeto e então escolha a opção "Manually select features"
40
40
vue create my-project-name
41
41
42
-
#If you already have a Vue CLI project without TypeScript, please add a proper Vue CLI plugin:
42
+
#Se você já tem um projeto com Vue CLI sem TypeScript, por favor adicione o plugin apropriado:
43
43
vue add typescript
44
44
```
45
45
46
-
Make sure that `script`part of the component has TypeScript set as a language:
46
+
Certifique-se que a parte `script`do componente tem o TypeScript definido como linguagem:
47
47
48
48
```html
49
49
<scriptlang="ts">
50
50
...
51
51
</script>
52
52
```
53
53
54
-
### Editor Support
54
+
### Suporte do Editor
55
55
56
-
For developing Vue applications with TypeScript, we strongly recommend using [Visual Studio Code](https://code.visualstudio.com/), which provides great out-of-the-box support for TypeScript. If you are using [single-file components](./single-file-component.html) (SFCs), get the awesome [Vetur extension](https://github.com/vuejs/vetur), which provides TypeScript inference inside SFCs and many other great features.
56
+
Para o desenvolvimento de aplicações Vue com TypeScript, nós recomendamento fortemente usar o [Visual Studio Code](https://code.visualstudio.com/), que fornece um excelente suporte para o TypeScript. Se você está usando [componentes Single File](./single-file-component.html) (SFCs), obtenha a incrível [extensão Vetur](https://github.com/vuejs/vetur), que provê a inferência do TypeScript dentro de SFCs e muitos outros ótimos recursos.
57
57
58
-
[WebStorm](https://www.jetbrains.com/webstorm/)also provides out-of-the-box support for both TypeScript and Vue.
58
+
O [WebStorm](https://www.jetbrains.com/webstorm/)também fornece um suporte pronto pra uso para ambos, TypeScript e Vue.
59
59
60
-
## Defining Vue components
60
+
## Definindo componentes Vue
61
61
62
-
To let TypeScript properly infer types inside Vue component options, you need to define components with `defineComponent`global method:
62
+
Para permitir o TypeScript inferir corretamente os tipos dentro das opções do componente Vue, você precisa definir os componentes com o método global `defineComponent`:
63
63
64
64
```ts
65
65
import { defineComponent } from'vue'
66
66
67
67
const Component =defineComponent({
68
-
//type inference enabled
68
+
//inferência de tipos habilitada
69
69
})
70
70
```
71
71
72
-
## Using with Options API
72
+
## Usando a API de Opções
73
73
74
-
TypeScript should be able to infer most of the types without defining types explicitly. For example, if you have a component with a number `count` property, you will have an error if you try to call a string-specific method on it:
74
+
O TypeScript deve ser capaz de inferir a maioria dos tipos sem defini-los explicitamente. Por exemplo, se você tem um componente com uma propriedade numérica `count`, você receberá um erro se tentar chamar um método específico de _string_ nela.
const result =this.count.split('') // => Property 'split' does not exist on type 'number'
84
+
const result =this.count.split('') // => A propriedade 'slit' não existe no tipo 'number'
85
85
}
86
86
})
87
87
```
88
88
89
-
If you have a complex type or interface, you can cast it using [type assertion](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions):
89
+
Se você tem um tipo complexo ou uma interface, pode convertê-lo(a) usando a [afirmação de tipo](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions):
Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of computed. For this reason, you may need to annotate the return type of computed properties.
113
+
Por causa da natureza circular dos arquivos de declaração do Vue, o TypeScript pode ter dificuldades para inferir os tipos de dados computados. Por esse motivo, você precisa anotar o tipo do retorno de propriedades computadas.
Vue does a runtime validation on props with a `type`defined. To provide these types to TypeScript, we need to cast the constructor with`PropType`:
145
+
O Vue faz uma validação em runtime em propriedades com um `type`definido. Para fornecer esses tipos para o TypeScript, precisamos converter o construtor com`PropType`:
If you find validator not getting type inference or member completion isn’t working, annotating the argument with the expected type may help address these problems.
173
+
Se você descobrir que o validador não está obtendo a inferência de tipo ou a conclusão do membro não está funcionando, anotar o argumento com o tipo esperado pode ajudar a resolver esse problema.
174
174
175
-
## Using with Composition API
175
+
## Usando com a API de Composição
176
176
177
-
On `setup()` function, you don't need to pass a typing to `props` parameter as it will infer types from`props`component option.
177
+
Na função `setup()`, você não precisa passar um tipo para o parâmetro `props`, pois os tipos serão inferidos da opção`props`do componente.
const result =year.value.split('') // => Property 'split' does not exist on type 'number'
208
+
const result =year.value.split('') // => Propriedade 'split' não existe no tipo 'number'
209
209
}
210
210
})
211
211
```
212
212
213
-
Sometimes we may need to specify complex types for a ref's inner value. We can do that by simply passing a generic argument when calling ref to override the default inference:
213
+
Algumas vezes, podemos precisar especificar tipos complexos para o valor interno de uma ref. Podemos fazer isso simplesmente passando um argumento genérico ao chamar ref para sobrescrever a inferência padrão:
214
214
215
215
```ts
216
-
const year =ref<string|number>('2020') //year's type: Ref<string | number>
216
+
const year =ref<string|number>('2020') //tipo do year: Ref<string | number>
217
217
218
218
year.value=2020// ok!
219
219
```
220
220
221
-
::: tip Note
222
-
If the type of the generic is unknown, it's recommended to cast `ref`to`Ref<T>`.
221
+
::: tip Nota
222
+
Se o tipo do genérico é desconhecido, é recomendado converter `ref`para`Ref<T>`.
223
223
:::
224
224
225
-
### Typing`reactive`
225
+
### Tipando`reactive`
226
226
227
-
When typing a `reactive` property, we can use interfaces:
227
+
Ao tipar uma propriedade `reactive`, podemos usar interfaces:
0 commit comments