0

Currently digging into Vue-3 composition api and wondering how to use types in detail (using TypeScript on top of vue).

The documentation isn't very accurate on this, since there is only a short description about how to do Strings. Of course according to that I could simply use type Object, but I wonder how to declare object properties, to tell TypeScript what keys belong to a related object - in class style api this could be done the TypeScript way ... is there any extended source about how to do properties in detail in composition api?

  • Maybe provide a little code snippet demonstrating what you're trying to achieve. An example can often illustrate a problem better than a long description. – Husam Ibrahim Nov 24 '20 at 14:02
  • In class style api I'd do it this way: @Prop() somePropertyName: { foo, bar }; So TypeScript/my IDE knows that my Object should contain the keys foo and bar. I could not find any description about how to achieve that using composition api – Irgend Son Hansel Nov 24 '20 at 14:11
  • ok you need to use `PropType`. I'll give you an example below. – Husam Ibrahim Nov 24 '20 at 14:16
  • @IrgendSonHansel Someone asked [similar question](https://stackoverflow.com/q/64831745/3634538) recently. My proposed solution there might help. – Yom T. Nov 24 '20 at 14:58

1 Answers1

2

Use PropType to provide strong type definitions for your props. Here's an example ..

import { defineComponent, PropType } from 'vue';

export default defineComponent({
  props: {
    myProp: Object as PropType<{ foo: string, bar: number }>,
  },
  setup(props) {
    ...
  }
});
Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28
  • Can you tell where this information can be found? Now I know how to handle objects but what about arrays & functions ...? – Irgend Son Hansel Nov 24 '20 at 15:55
  • 1
    @IrgendSonHansel Same thing. See [Annotating Props](https://v3.vuejs.org/guide/typescript-support.html#annotating-props) in the official guide. – Husam Ibrahim Nov 24 '20 at 15:59