Subscribe on changes!

Typing ref() with a class with private methods gives typescript error when passed as argument to another function

avatar
Jan 27th 2023

Vue version

3.2.45

Link to minimal reproduction

https://sfc.vuejs.org/#eNpNUc1qAjEQfpUhlyrU3Z63KohtoeeWXoyHuM66kc0kzGRtRXz3JusPQg6TyffHl5NahFAcelSVmkrNNkQQjH2AztBuplUUreaarAueI5yAsYEzNOwdPCXa06smTXVnRGDZS/RumWdNJ00AfxVQ7zbIMIOXAQkQ2B5MRKgH9EdP9Wic9wMBoCzvCIex9du8PmtKR1OH8cpbMJtjUk1xpg++q/V8tFqPB6smSUfrCSJKHHwMc/WYMiGvQWtP4jssOr/LqCwwGKY0360V6CwhSOt/BQwBMnsGS+CO8Pn2DqOfr6XfYhK7Wz2kLA6m6zFLTstLw3P1rC6FTpwJxV48pfqHIPr6kFqvbpVolYrOd63aGINUZSlNnT9tL4XnXZmmgnuK1mGB4iYbTkGRk7BWt/rU+R+aAKwP

Steps to reproduce

TS version: v4.1.5 IDE: VSCode Extensions: Volar, Typescript Vue Plugin

To reproduce, copy/paste this code inside a .vue file:

// Test.vue

<script setup lang="ts">
import { ref } from 'vue';

class CustomClass
{
  x: number = 0;

  private customFunc()
  {
    // private method
  }
}

let customArray = ref<CustomClass[]>([]);

function testFunc(arr: CustomClass[])
{
  console.log(arr);
}

testFunc(customArray.value);
</script>

The last line of that code snippet will give a Typescript error saying:

Argument of type '{ x: number; }[]' is not assignable to parameter of type 'CustomClass[]'.
  Property 'customFunc' is missing in type '{ x: number; }' but required in type 'CustomClass'.
Screenshot 2023-01-26 at 10 14 26 PM

What is expected?

I would expect to be able to pass an array of CustomClass objects to the function without my IDE showing a Typescript error

What is actually happening?

My IDE is showing a Typescript error and says "customFunc" is missing from the expected type

System Info

System:
    OS: macOS 13.1
    CPU: (8) arm64 Apple M1
    Memory: 61.08 MB / 8.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.17.1 - /usr/local/bin/node
    Yarn: 1.22.19 - ~/homebrew/bin/yarn
    npm: 8.15.0 - ~/homebrew/bin/npm
    Watchman: 2022.10.24.00 - /Users/ccmetz/homebrew/bin/watchman
  Browsers:
    Chrome: 107.0.5304.87
    Firefox: 105.0.1
    Safari: 16.2

Any additional comments?

No response

avatar
Jan 27th 2023

You can try using type assertions, like this testFunc(customArray.value as CustomClass[]);

avatar
Jan 27th 2023

@code-ManL appreciate the comment! I know that type casting will make the error go away but was mostly curious if this is something that can be addressed in a future version of Vue. After doing some more digging, I stumbled across #2981 and it appears that it would be pretty difficult.