Home > database >  Vue 2 / Typescript, how to cast a prop inline?
Vue 2 / Typescript, how to cast a prop inline?

Time:12-03

I have a Vue 2 NuxtJS project setup with Typescript and I'd like to take advantage of the unknown keyword in Typescript.

In my component, I receive a prop declared like so

props: { 
  items: {
    type: Array as () => LabelValuePair[],
    required: true,
  },
},

LabelValuePair is declared here

interface LabelValuePair {
  label: string;
  value: unknown;
}

And inside my template, I'd like to use something like this

<li v-for="item in items" :key="item.value as string">
  <span>
    {{ item.label }}: <strong>{{ item.value }}</strong>
  </span>
</li>

The thing is, as well as the ternary operator, the as Typescript keyword is not recognize as valid syntax by the vue compiler.

Is there a solution or a workaround at least to avoid doing something silly like the following?

setup(props) {
  const castItems = props.items.map((item) => ({
    ...item,
    value: item.value as string,
  }));

  return { castItems };
},

CodePudding user response:

If LabelValuePair is supposed to be reused and is expected to have string value in a prop, this is the case for generic type:

interface LabelValuePair<T = unknown> {
  label: string;
  value: T;
}

and

  items: {
    type: Array as PropType<LabelValuePair<string>[]>,
    required: true,
  },
  • Related