logue / vite-vue2-vuetify-ts-starter

@vitejs template for @vuejs 2+@vuetifyjs+TypeScript
MIT License
84 stars 31 forks source link

feature request: auto infer prop types #2

Closed ngjuping closed 2 years ago

ngjuping commented 2 years ago

Hi logue,

According to this link: https://github.com/kaorun343/vue-property-decorator/issues/303

We can make vue-property-decorator infer prop type from TypeScript types.

Why is this significant:

  1. First, a dry code is a good code, and declaring props like this: @Prop({type: Boolean}) readonly trigger: boolean is not dry.
  2. One can easily forget that explicit prop type declaration is required, leading to unexpected behavior, e.g. a Boolean prop defaults to false but if not explicitly declared, it will result in empty string "" instead of false

Hopefully this gets implemented.

Best regards, Ju Ping

logue commented 2 years ago

I have migrated to the composition api, so it seems that vue-property-decorator is left for compatibility, but after the migration, the location that was pointed out was a warning, so this release (0.5.0) I fixed it in.

ngjuping commented 2 years ago

Thanks for the response! It seems that there are practical issues to use reflect-metadata to infer prop types automatically when the types are custom interfaces, which is stated here https://github.com/kaorun343/vue-property-decorator/issues/354. As your plan is to move forward with composition-api, I will start writing my components as such. One more follow-up confusion though, can you point out the place where warning occurred?

logue commented 2 years ago

There was a warning in the previous writing style of @Props. Actually, the content of this is an alias of the content inside the variable {} in the following way of writing.

props {
  variable: {type: String, default: ''}
}

So, the warning is that the values of props must be type and defalut.

For objects and arrays, defaults seems to be a function.

props {
  variable: {type: Object, default: () => { return undefined; } },
}
props {
  variable1: {type: Object as () => SomeObject, default: () => { return undefined; } },
  variable2: {type: Object as PropType<SomeObject>, default: () => { return undefined; } },
}

So, in the case of @Prop, I think it is correct to enter the following in the same way.

@Props({type: Object as () => SomeObject, default: () => { return undefined; } })
variable1! :SomeObject;
ngjuping commented 2 years ago

I've been writing my props exactly like this. Thanks for making things clear!