Subscribe on changes!

computed and ComputedGetter are not type-safe

avatar
Apr 10th 2022

Version

3.2.31

Reproduction link

www.typescriptlang.org/play

Steps to reproduce

  1. Import computed from vue
  2. Create a function that takes an argument
  3. Pass this function directly to computed
  4. Compile the code with typescript
import { computed } from 'vue';

function takes(a: number): string {
    return a.toString();
};

const shouldFail = computed(takes); // works, should fail
const fails = computed(() => takes()); // fails as it should

What is expected?

Typescript should fail to compile with the error "Expected x arguments, but got 0."

What is actually happening?

Typescript compiles the code without an error. Code crashes at runtime.


The problem is that ComputedGetter, which is the first argument to computed, has the type

export declare type ComputedGetter<T> = (...args: any[]) => T;

while it should have the type

ComputedGetter<T> = () => T;

You can pass the function as () => func() to ensure that if an argument is added to the function, typescript will tell you that it is missing, but that seems unnecessarily verbose.