Skip to content

Commit f73c10f

Browse files
committed
Initial section on vue data
1 parent 437f4af commit f73c10f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,53 @@ export default class InfoCard extends Vue {
195195
</script>
196196
```
197197

198+
## Data Properties
199+
200+
You can enforce types on Vue data properties by annotating the return data object:
201+
202+
```ts
203+
interface Post {
204+
title: string;
205+
contents: string;
206+
likes: number;
207+
}
208+
209+
export default Vue.extend({
210+
data(): { newPost: Post } {
211+
return {
212+
newPost: {
213+
title: "",
214+
contents: "",
215+
likes: 0
216+
}
217+
};
218+
}
219+
});
220+
```
221+
222+
It might be tempting to annotate your Vue data properties using `as` like this:
223+
224+
```ts
225+
interface Post {
226+
title: string;
227+
contents: string;
228+
likes: number;
229+
}
230+
231+
export default Vue.extend({
232+
data() {
233+
return {
234+
newPost: {
235+
title: "",
236+
contents: "",
237+
likes: 0
238+
} as Post // ❌ Avoid doing this
239+
};
240+
}
241+
});
242+
```
243+
Note that [type assertion](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions) like this does not provide any type safety. If for example, the `contents` property was missing in `newPost`, TypeScript would not catch this error.
244+
198245
# Other Vue + TypeScript resources
199246
- Views on Vue podcast - https://devchat.tv/views-on-vue/vov-076-typescript-tell-all-with-jack-koppa/
200247
- Focuses a lot on class components and vue-property-decorator - https://blog.logrocket.com/how-to-write-a-vue-js-app-completely-in-typescript/

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy