You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import{ExternalProps}from'./typeUtils.ts'import{PropTypes}from'vue'// Example custom typesinterfaceUser{name: string}interfacePost{title: string}constmySharedProps={user: {type: ObjectasPropType<User>,default: ()=>({name: 'Tom'})},post: {type: ObjectasPropType<Post>,required: true,},}asconst// <= THIS IS NECESSARY TO DETECT REQUIRED PROPS CORRECTLY!exporttypeMySharedProps=ExternalProps<typeofmySharedProps>//This is the resulting type:typeMySharedProps={user?: User|undefined// has default value internally, but from parent's perspective it's optionalpost: Post// required}
A little bit on how this works:
ExtractPropTypes gives you almost what you want, but the resulting interface has props with a default value marked as required. This is because this interface is the internal props interface - this.$props, where props with default values are guaranteed to be present.
So we need to make these optional. How?
ExtractDefaultPropTypes gives us an interface with only those props that have default values
We then use the keys of this interface with keyof ...
and make these keys optional on the interface provided by ExtractPropTypes
For the last step I use SetOptional from the amazing type-fest collection of useful types, but I'm sure there's a SO answer out there that explains how to make properties on an interface optional if you don't want to add another dependency.
Also, yes - I think it would make real sense to have this in the core types.
@mesqueeb This is possible with a bit of type magic, yes.
Usage:
A little bit on how this works:
ExtractPropTypes
gives you almost what you want, but the resulting interface has props with a default value marked as required. This is because this interface is the internal props interface -this.$props
, where props with default values are guaranteed to be present.So we need to make these optional. How?
ExtractDefaultPropTypes
gives us an interface with only those props that have default valueskeyof
...ExtractPropTypes
For the last step I use
SetOptional
from the amazingtype-fest
collection of useful types, but I'm sure there's a SO answer out there that explains how to make properties on an interface optional if you don't want to add another dependency.Also, yes - I think it would make real sense to have this in the core types.
Originally posted by @LinusBorg in vuejs/core#4294 (comment)
The text was updated successfully, but these errors were encountered: