Vue-next: improve type for unwrap computed

Created on 15 Apr 2020  路  5Comments  路  Source: vuejs/vue-next

What problem does this feature solve?

I'm using vue3 with typescript like todomvc,
but when I refer to its properties, type lost.

const state = reactive({
  a: 1,
  b: computed(() => {
    return state.a + 1
  }) 
})

type:
const state: any

It looks like it's referencing its own type and it no type yet, but I want to define the required property on state without declaring the full state type.

Is there a way to keep the type as declaring the original object?

const state = {
  a: 1,
  b: () => {
    return state.a + 1
  }
}

type:
const state: {
    a: number;
    b: () => number;
}

What does the proposed API look like?

const state: {
    a: number;
    b: number;
}
enhancement types has workaround wontfix

Most helpful comment

image

I think the error message is quite clear
'x' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)

An easy workaround would be manually typing computed's callback:
image

All 5 comments

I doubt we can do anything with our types, the problem can be boil down to

function f<T>(a: T): T {
  return {} as any
}
function c<T>(d: () => T): T {
  return {} as any
}

const x = f({
  a: 1,
  ff: c(() => {
    return x.a;
  })
})

typescript playground

My guess is the error 7022 happens because computed returns T (and T is resolved as the return type of the method) meaning to typescript the method will run straight away, making the variable not initiated.

to typescript using computed is the same as:

const state = {
  a: 1,
  b: state.a
}

I think this cause by type loop

As a supplement, the reason I think is that when call this arrow function as an argument of c, typescript can't infer the type of this arrow function.

() => {
    return x.a;
}

image

I think the error message is quite clear
'x' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)

An easy workaround would be manually typing computed's callback:
image

Think we can close this as concensus is that this hits a limitation in TS, and we have a good workaround with annotating the return value

Was this page helpful?
0 / 5 - 0 ratings