Skip to content

Commit 51282d2

Browse files
authored
Merge pull request #8 from typescript-cheatsheets/data-props
Initial section on vue data
2 parents 437f4af + f73c10f commit 51282d2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

README.md

+47
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)