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);
CodePudding user response:
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