Cast from Object for an object created in Typescript

Asked

Viewed 37 times

1

Problem

Good afternoon! it is possible, in typescript, to give a cast of a object to a class I created? I need precisely to validate whether the fields exist or not, and if they are filled in correctly, then the risk of a property not existing is not a problem.

Context

I am doing an API in typescript and came across a problem: One of the parameters I receive is an object that can vary according to other fields, and each of the objects has nothing to do with the other.

After much break the head (I wanted to validate everything using decorators, but I could not find a solution), I ended up leaving him as a object even

config: object;

Beauty! However, to validate, I thought about creating the object with the constructor (or just having a validation method, in my context does not make a difference). I started doing the following:

constructor(config: object)
{
    if(config.property !== undefined && config.property > 3)
            //ok
}

Which brings me back to error Property 'queryId' does not exist on type 'object'.ts(2339). I understand that the typescript itself limits these actions, but I really don’t know how to proceed. My idea was to cast, is this the correct approach? And if so, how do I do it?

1 answer

1


I don’t usually program in Typescript, but one of the things you can do is check if a certain property exists inside the object you’re receiving.

For example:

constructor (config: object) 
{
    if ("id" in config) 
    {
        // Aqui é possível acessar a propriedade 'id'
        validar(config.id)
    }
    else if ("nome" in config) 
    {
        // Aqui é possível acessar a propriedade 'nome'
        validar(config.nome)
    }
}

Although I don’t have as much proficiency with Typescript I would indicate that you still used well-defined interfaces in the constructor instead of object, because this will surely make it much easier for those who consume this API since they will clearly have what they can or cannot pass as a parameter.

If this constructor accepts different types, Typescript has a feature called Union Types that can help.

Adapting the above example to use Union Types.

constructor (config: ConfigA | ConfigB) 
{
    if ("id" in config) 
    {
        validar(config.id)
    }
    else if ("nome" in config) 
    {        
        validar(config.nome)
    }
}

This way, that to use this constructor knows that it accepts objects that match the interface ConfigA or with the interface ConfigB.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.