Skip to content

Commit 8c9bc9b

Browse files
committed
docs(ts-support): annotating props with validators and default values
1 parent 3ad6eaf commit 8c9bc9b

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

src/guide/typescript-support.md

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ interface ComplexMessage {
177177
okMessage: string
178178
cancelMessage: string
179179
}
180+
180181
const Component = defineComponent({
181182
props: {
182183
name: String,
@@ -185,17 +186,43 @@ const Component = defineComponent({
185186
type: Function as PropType<() => void>
186187
},
187188
message: {
188-
type: Object as PropType<ComplexMessage>,
189-
required: true,
190-
validator(message: ComplexMessage) {
191-
return !!message.title
192-
}
189+
type: Object as PropType<ComplexMessage>
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+
const Component = defineComponent({
205+
props: {
206+
numbersA: {
207+
type: Array as PropType<number[]>,
208+
// Make sure to use arrow functions
209+
default: () => [],
210+
validator: (numbers: number[]) =>
211+
numbers.every(x => typeof x === 'number')
212+
},
213+
numbersB: {
214+
type: Array as PropType<number[]>,
215+
// Or provide an explicit this parameter
216+
default(this: void) {
217+
return []
218+
},
219+
validator(this: void, numbers: number[]) {
220+
return numbers.every(x => typeof x === 'number')
221+
}
222+
}
223+
}
224+
})
225+
```
199226

200227
## Using with Composition API
201228

0 commit comments

Comments
 (0)