Composition-api: Typing Object props

Created on 20 Jan 2020  路  2Comments  路  Source: vuejs/composition-api

As per https://github.com/vuejs/vue/issues/9692#issue-420446580, I expected to be able to type Object props using TypeScript as follows:

<script lang="ts">
import { PropType } from 'vue';
import { createComponent } from '@vue/composition-api';

interface Options {
    labelOn: string;
    labelOff: string;
}

export default createComponent({
    props: {
        options: {
            type: Object as PropType<Options>,
            default: false
        }
    },
    setup(props) {
        props.options;
    }
});
</script>

However, as soon as I add as PropType<Options> to the mix, I get an error in Vetur and Vue CLI serve:

No overload matches this call.
  Overload 1 of 2, '(options: ComponentOptionsWithoutProps<never, unknown>): VueProxy<never, unknown>', gave the following error.
    Type '{ value: { type: BooleanConstructor; default: null; }; readonly: { type: BooleanConstructor; default: boolean; }; options: { type: PropType<Options>; default: boolean; }; }' is not assignable to type 'undefined'.

I saw that https://github.com/vuejs/composition-api/issues/208 mentioned adding support for the above for function calls, but I'm wondering if the "original" functionality exists in the Composition API to begin with.

image

image

image

Is what I'm trying to do supported, or am I using it wrong? If that's the case, how can one type Object type props properly in TypeScript? Thanks for all your great work 馃檪

Most helpful comment

This package exports its own PropType type which you should use when using this plugin

All 2 comments

The function workaround mentioned in https://github.com/vuejs/vue/pull/6856#issuecomment-417183243 luckily does work in this instance, eg:

<script lang="ts">
import { PropType } from 'vue';
import { createComponent } from '@vue/composition-api';

type Options = {
    labelOff: string;
    labelOn: string;
};

export default createComponent({
    props: {
        options: {
            type: Object as () => Options,
            required: true
        }
    },
    setup(props) {
        props.options;
    }
});
</script>

This package exports its own PropType type which you should use when using this plugin

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sseeland picture sseeland  路  4Comments

spaceemotion picture spaceemotion  路  6Comments

sapphi-red picture sapphi-red  路  4Comments

banricho picture banricho  路  3Comments

carlmjohnson picture carlmjohnson  路  5Comments