Skip to content

Async data return typed data with TypeScript #7884

@deozza

Description

@deozza

Versions

  • nuxt: ^2.14.1
  • node: 14.7.0

Reproduction

// ~/class/user/user
export class User{
/*
properties instanciation + constructor
*/
	public getCleanedForRequest() {
                return 'foo';
	}
}
// ~/pages/user.vue
<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";

import {User} from "~/class/user/user";

interface UserSpecificVueInterface{
	user: User,
	loading: boolean,
	error: any
}

@Component({
	async asyncData({$axios, $auth, route}): Promise<UserSpecificVueInterface>{
		const link = '/link/to/resource';
		const token = $auth.getToken('local');
		const userFromApi = await $axios.$get(link, {
			headers: {
				Authorization: token
			}
		});

		return {
			user: new User(userFromApi),
			loading: false,
			error: null
		};
	}
})
export default class UserSpecificVue extends Vue implements UserSpecificVueInterface{
	user: User;
	loading: boolean = false;
	error: any = null;

	async updateUser(){

		this.loading = true;
                console.log(this.user instanceof User); //should be true, returns false
                console.log(this.user.getCleanedForRequest()); // should echo 'foo', returns `getCleanedForRequest() is not a function of user`    
	}
}

</script>
Additional Details

What is Expected?

I want to use asyncData function to fetch a resource from an API at the page loading. This resource is then used as a typed property with a custom TypeScript class, with its properties and its functions.

What is actually happening?

The property is not typed according to the custom TypeScript class

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