Skip to content

How to properly type reactive object #328

@MartinMalinda

Description

@MartinMalinda

Let's say I have a reactive object like this:

const person = reactive({
 firstName: 'John',
 lastName: 'Doe',
 fullName: computed(() => `${person.firstName} ${person.lastName}`)
});

I'm struggling to find the correct ways to type this.

I could start right away with

interface Person {
 firstName: string;
 lastName: string;
 fullName: string;
}

That's how the end result is being used.

But this does not work because fullName is Ref<string>.

I could type it as Ref<string> in the interface but then the usage of this object would be wrong. TS would require person.fullName.value.

So far the best workaround I could think of is creating a wrap function like this:

// only to be used within `reactive()`
function comp<T>(cb: () => T) : T {
  return (computed<T>(() => cb()) as unknown) as T;
}

// or more general
function u<T>(ref: Ref<T>) : T {
  return (ref as unknown) as T;
}

const person : Person = reactive({
 firstName: 'John',
 lastName: 'Doe',
 fullName: u(computed(() => `${person.firstName} ${person.lastName}`)) 
});

It feels a bit hacky though, is there a better way?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions