Skip to content

Expanding ComputedGetter's return type #738

Closed
@shirakomamu

Description

I am attempting to use a computed value in the setup() block of a component, such as follows:

const store = useStore();

const computedItem = computed({
  get(): string | null {
    return store.getters["getterHere"]; // string, sometimes null
  },
  set(newValue: string): void {
    store.commit("setterHere", newValue);
  },
});

The getter normally returns a string, but as it also can sometimes be null. I therefore annotated the getter's return as string | null. (The value in the store is initialized elsewhere, hence the possibility of the null value.)

However, I'm getting a Vetur error 2769 on the get() due to the return value of null not being assignable to string.

I believe this error occurs due code in the following files:

  1. https://github.com/vuejs/composition-api/blob/b7c7211e560f5966a563dc393ca6f30321a6416b/src/component/componentOptions.ts
  2. https://github.com/vuejs/composition-api/blob/7955e2879754a26db57ca7ef7da35d3098c84480/src/apis/computed.ts

In this code, the type that is used for the argument for ComputedSetter is reused as the return type of the ComputedGetter. So in this case, the TypeScript error occurs because it is attempting to coerce the return type of the get function to string instead of string | null.

Might it be possible to allow the getter function's return type to be a superset containing the type passed into the setter?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions