Subscribe on changes!

`defineProps` literal types is parsed to string types

avatar
Sep 10th 2021

What problem does this feature solve?

<script setup lang="ts">
type Props = {
  color: 'blue' | 'red'
}

defineProps<Props>()
</script>

After compiler parse:

image

color prop will lose literal types

What does the proposed API look like?

import { defineComponent as _defineComponent, PropType } from 'vue'
type Props = {
  color: 'blue' | 'red'
}

const _sfc_main = /*#__PURE__*/_defineComponent({
props: {
  color: { type: String as PropType<'blue' | 'red'> , required: true }
  // color: { type: String as PropType<Props['color']> , required: true }
},
setup(__props: Props, { expose }) {
  // ...
}
avatar
Sep 10th 2021

You don't access the defineProps returned value.The type is meaningless so it was abandoned by the sfc-compiler.

This will generate the correct type.

<script setup lang="ts">
type Props = {
  color: 'blue' | 'red'
}

const props = defineProps<Props>()  // <- access the return value
</script>
avatar
Sep 10th 2021

@Bigfish8 Thanks for your reply.

<script setup lang="ts">
type Props = {
  color: 'blue' | 'red' | 'purple'
}

const props = defineProps<Props>()
</script>

After parse then got the following:

image

And the declaration like this:

declare const _sfc_main: DefineComponent<{
    color: {
        type: StringConstructor;
        required: true;
    };
}, {
    props: {
        color: 'blue' | 'red' | 'purple';
    };
}, unknown, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, Record<string, any>, string, VNodeProps & AllowedComponentProps & ComponentCustomProps, Readonly<{
    color?: unknown;
} & {
    color: string;
} & {}>, {}>;

When using this component:

image