Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically adding properties to objects and return new type with the properties

I have the following code. And I don’t know why it doesn’t work.
I want to add properties whether to an array of objects or to a single object.
After that I want to have the autocompletion from Typescript available.
I’m definitely not an expert in Typescript.

function addProperties<T extends object, S extends object>(data: T[], properties: S): (T & S)[];
function addProperties<T extends object, S extends object>(data: T, properties: S): T & S {
    if (Array.isArray(data)) {
        return data.map(item => Object.assign(item, properties));
    }
    return Object.assign(data, properties);
}

interface User {
    firstname: string;
    lastname: string;
}

let user: User = {
    firstname: 'John',
    lastname: 'Doe',
};

let users: User[] = [
    {
        firstname: 'John',
        lastname: 'Doe',
    },
    {
        firstname: 'Peter',
        lastname: 'Pan',
    }
];

const newUsers = addProperties(users, {
    foo: 'bar',
    active: true
});

const newUser = addProperties(user, {
    foo: 'bar',
    active: true
});

console.log(newUser.firstname);
console.log(newUser.lastname);
console.log(newUser.foo);
console.log(newUser.active);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That overload isn’t right. You should have multiple call signatures, followed by one implementation that accepts all possible call signatures.

What you have is one call signature, followed by the implementation that has a different signature. That’s probably not what you intended.

I think you want this:

function addProperties<T extends object, S extends object>(data: T[], properties: S): (T & S)[];
function addProperties<T extends object, S extends object>(data: T, properties: S): T & S;

function addProperties<T extends object, S extends object>(data: T | T[], properties: S): (T & S) | (T & S)[] {
    if (Array.isArray(data)) {
        return data.map(item => Object.assign(item, properties));
    }
    return Object.assign(data, properties);
}

Which compiles without errors. See Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading