A
A
Andrew2022-01-20 01:17:37
typescript
Andrew, 2022-01-20 01:17:37

How to make friends a type/interface with a class in TS?

The task is to convert the data stored on the back into a class that will hang additional methods for working with data and some additional fields that are needed only as part of the work inside the front, but are not needed on the back.

More or less like this:

type UserType = {
    firstname: string 
    lastname: string
    age: number
}

class User {
    id: string
    firstname: string
    lastname: string
    age: number

    constructor(user: UserType) {
        this.id = nanoid()
        this.firstname = user.firstname
        this.lastname = user.lastname
        this.age = user.age
    }

    someMethod() {
        // some work
    }

    someMethod2() {
        // some work 2
    }

    toObject(): UserType {
        const user_object: UserType = {
            // blah blah
        }

        return user_object
    }
}


More precisely, this is what I came up with. But do they do it, is it normal practice? If this is OK, then how are the entities named in such cases? I know that it is customary (was) to call interfaces with a capital I before the name, I have not seen anything like this for types. Plus, I heard that this is an outdated practice, which is why it is even more misleading.

UPD:
How appropriate is it to inherit from a type/interface when creating a class? Again, in my particular case (maybe I'm doing everything wrong and wrong, and generally a fool and it should be completely different):

class User implements UserType { // code }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question