typescriptvue.js

How to declare type of props in vuejs with typescript?


Here's the snippet of code

<tr v-for="(log, index) in logs">
        <td>{{ index + 1 }}</td>
        <td>{{ log.timestamp }}</td>
        <td>{{ log.logType }}</td>
        <td>{{ log.logMessage }}</td>
      </tr>



defineProps({
  logs: {
    type: [Array],
    required: true
  }
})

Here log would be

{ timestamp : "2024-05-07 08:51:06",
logType : "INFO",
logMessage : "mailbox allocated for rsvp"
}

I'm new to typescript and I'm getting the below warning for log.timestamp, log.logType and log.logMessage during build

'log' is of type 'unknown'.

What should be the type of logs here?


Solution

  • Assuming log is of type

    type LogEntry = {
      timestamp: string;
      logType: string;
      logMessage: string;
    };
    

    as answered in your previous question.

    You can do it

    const props = defineProps({
      logs: {
        type: Array as PropType<Array<LogEntry>>,
        required: true,
      },
    });
    

    Don't forget to import PropType.

    import type { PropType } from 'vue';
    

    Docs

    If you didn't have a type/interface for some reason you could declare it straight away like

    logs: {
        type: Array as PropType<Array<{timestamp: string, logType: string, logMessage: string}>>,
        required: true,
      },