Search code examples
node.jstypescript

Remove propertis not present in interface with nodejs typescript


I'm using node.js with typescript and I have a question

It is possible to remove properties that are not present in an interface when casting an object.

interface IFooReal {
                    prop1: string;
                  }

const objTMP = {prop1: 'foo001', prop2: 'foo002', prop3: 'foo003'};

cont barr = objTMP as IFooReal; //or do someting to remove properties not presente in interface

console.log(barr);

When execute console.log(barr); the result is {prop1: 'foo001'}


Solution

  • Using a type assertion like objTMP as IFooReal doesn't change anything about objTMP, it only tells TypeScript "please treat this as an IFooReal".

    TypeScript's purpose is just annotating your code in a way that lets it check it for type safety. It doesn't modify your code, or add any execution of its own (with limited exceptions, like enums). When TypeScript is compiled into JavaScript, the process is mostly just removing those annotations.

    If you want to remove all but a subset of properties from an object, then you will need to iterate through its properties and remove any that don't match the properties you want to keep. Something like this, for example:

    interface IFooReal {
        prop1: string;
    }
    
    const objTMP = {
        prop1: 'foo001',
        prop2: 'foo002',
        prop3: 'foo003'
    };
    
    // You may want to get this by calling Object.keys() on another object?
    const propertiesToKeep = ['prop1'];
    
    for (let prop in objTMP) {
        if (propertiesToKeep.includes(prop) === false) {
            delete (objTMP as {[key:string]: any})[prop];
        }
    }
    
    console.log(objTMP);
    

    TypeScript playground

    I've had to use the type assertion objTMP as {[key: string]: any}) here because otherwise TypeScript would complain that you're attempting to access a property on objTMP using a variable with type string, when TypeScript has implicitly typed it as { prop1: string, prop2: string, prop3: string } so only values of type 'prop1'|'prop2'|'prop3' can be used to access its properties.

    That type assertion basically just tells TypeScript "let me try to access properties on this object using any string as the key, and don't worry about what type that property has".