diff --git a/src/guide/typescript-support.md b/src/guide/typescript-support.md index 2ea5e3c3ec..8aa2c28ddb 100644 --- a/src/guide/typescript-support.md +++ b/src/guide/typescript-support.md @@ -172,11 +172,12 @@ Vue does a runtime validation on props with a `type` defined. To provide these t ```ts import { defineComponent, PropType } from 'vue' -interface ComplexMessage { +interface Book { title: string - okMessage: string - cancelMessage: string + author: string + year: number } + const Component = defineComponent({ props: { name: String, @@ -184,18 +185,52 @@ const Component = defineComponent({ callback: { type: Function as PropType<() => void> }, - message: { - type: Object as PropType, - required: true, - validator(message: ComplexMessage) { - return !!message.title - } + book: { + type: Object as PropType, + required: true } } }) ``` -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. +::: warning +Because of a [design limitation](https://github.com/microsoft/TypeScript/issues/38845) in TypeScript when it comes +to type inference of function expressions, you have to be careful with `validators` and `default` values for objects and arrays: +::: + +```ts +import { defineComponent, PropType } from 'vue' + +interface Book { + title: string + year?: number +} + +const Component = defineComponent({ + props: { + bookA: { + type: Object as PropType, + // Make sure to use arrow functions + default: () => ({ + title: "Arrow Function Expression" + }), + validator: (book: Book) => !!book.title + }, + bookB: { + type: Object as PropType, + // Or provide an explicit this parameter + default(this: void) { + return { + title: "Function Expression" + } + }, + validator(this: void, book: Book) { + return !!book.title + } + } + } +}) +``` ## Using with Composition API