Skip to content
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

Support TypeScript as in props #2252

Open
3 tasks done
brigand opened this issue Sep 4, 2020 · 2 comments
Open
3 tasks done

Support TypeScript as in props #2252

brigand opened this issue Sep 4, 2020 · 2 comments

Comments

@brigand
Copy link

brigand commented Sep 4, 2020

  • I have searched through existing issues
  • I have read through docs
  • I have read FAQ

Info

  • Platform: MacOS
  • Vetur version: Published around Sep 2 2020
  • VS Code version: 1.48.2

Problem

This commit leaves no clear way to have a TypeScript type as the prop type while also having the property be optional.

Reproducible Case

Given the following...

interface Foo {
  bar: string
}

function optionalProp<T>(type: Vue.PropType<T>): Vue.PropOptions<T> {
    return { type, required: false };
}

You could define an optional prop as this:

// TheComponent.vue
props: {
  foo: { type: Object, required: false } as Vue.PropOptions<Foo>
}

Or this:

// TheComponent.vue
props: {
  foo: optionalProp<Foo>(Object)
}

However both of these cause a warning in vetur if the prop is omitted when using TheComponent.

<TheComponent> misses props: foo

In the first example, this is because the syntax tree for the node after foo: is { "type": "AsExpression", "expression": { "type": "ObjectExpression", … }, while the lint here expects it to be exactly an ObjectExpression.

In the second example, we have a CallExpression.

Neither of these are required props, and the warning applying by default seems a bit aggressive. It leads to the entire template block being yellow underlined in many cases.

As an approximation, it might be more useful to match positively on { "type": "Identifier", "text": /^[A-Z]/ } instead of matching negatively on an object literal, which catches Object, Array, conventionally named custom classes, etc. It wouldn't match localVariable, optionalProp<Foo>(Object), { type: String } as T, and so on.

@tobiasdalhof
Copy link

That's how I add type support to my props

props: {
  foo: {
    type: Object as () => FooInterface
  },
  bar: {
    type: Array as () => BarInterface[]
  }
}

@brigand
Copy link
Author

brigand commented Sep 4, 2020

Yeah, this all works fine for props that are required, like in your example. The issue is that the patterns for optional props with TypeScript are interpreted as required props by Vetur.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants