Skip to content

Commit 9e5f13e

Browse files
JensDllfimion
authored andcommitted
docs(ts-support): annotating props with validators and default values (#730)
* docs(ts-support): annotating props with validators and default values * docs(ts-support): annotating props added prop for number array * added missing comma * docs(ts-support): annotating props use the Book interface in examples
1 parent db5691d commit 9e5f13e

File tree

1 file changed

+45
-10
lines changed

1 file changed

+45
-10
lines changed

src/guide/typescript-support.md

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -172,30 +172,65 @@ Vue does a runtime validation on props with a `type` defined. To provide these t
172172
```ts
173173
import { defineComponent, PropType } from 'vue'
174174

175-
interface ComplexMessage {
175+
interface Book {
176176
title: string
177-
okMessage: string
178-
cancelMessage: string
177+
author: string
178+
year: number
179179
}
180+
180181
const Component = defineComponent({
181182
props: {
182183
name: String,
183184
success: { type: String },
184185
callback: {
185186
type: Function as PropType<() => void>
186187
},
187-
message: {
188-
type: Object as PropType<ComplexMessage>,
189-
required: true,
190-
validator(message: ComplexMessage) {
191-
return !!message.title
192-
}
188+
book: {
189+
type: Object as PropType<Book>,
190+
required: true
193191
}
194192
}
195193
})
196194
```
197195

198-
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.
196+
::: warning
197+
Because of a [design limitation](https://github.com/microsoft/TypeScript/issues/38845) in TypeScript when it comes
198+
to type inference of function expressions, you have to be careful with `validators` and `default` values for objects and arrays:
199+
:::
200+
201+
```ts
202+
import { defineComponent, PropType } from 'vue'
203+
204+
interface Book {
205+
title: string
206+
year?: number
207+
}
208+
209+
const Component = defineComponent({
210+
props: {
211+
bookA: {
212+
type: Object as PropType<Book>,
213+
// Make sure to use arrow functions
214+
default: () => ({
215+
title: "Arrow Function Expression"
216+
}),
217+
validator: (book: Book) => !!book.title
218+
},
219+
bookB: {
220+
type: Object as PropType<Book>,
221+
// Or provide an explicit this parameter
222+
default(this: void) {
223+
return {
224+
title: "Function Expression"
225+
}
226+
},
227+
validator(this: void, book: Book) {
228+
return !!book.title
229+
}
230+
}
231+
}
232+
})
233+
```
199234

200235
## Using with Composition API
201236

0 commit comments

Comments
 (0)