Skip to content

docs(ts-support): annotating props with validators and default values #730

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 8, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 45 additions & 10 deletions src/guide/typescript-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,30 +172,65 @@ 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,
success: { type: String },
callback: {
type: Function as PropType<() => void>
},
message: {
type: Object as PropType<ComplexMessage>,
required: true,
validator(message: ComplexMessage) {
return !!message.title
}
book: {
type: Object as PropType<Book>,
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<Book>,
// Make sure to use arrow functions
default: () => ({
title: "Arrow Function Expression"
}),
validator: (book: Book) => !!book.title
},
bookB: {
type: Object as PropType<Book>,
// 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

Expand Down