Reputation: 1628
I would like to remove the tslint error I get on the following (in the object desctructuring parameter):
export function renameProperty(
oldProp: string,
newProp: string,
{[oldProp]: old, ...others}
): any {
return {
[newProp]: old,
...others
};
}
The error I get is on line 5:
TSLint: expected parameter: '{[oldProp]: old, ...others}' to have a typedef (typedef)
of course, I could do the following, but I'd rather simply do what satisfies Typescript's typing requirements.
export function renameProperty(
oldProp: string,
newProp: string,
// tslint:disable-next-line:typedef
{[oldProp]: old, ...others}
): any {
return {
[newProp]: old,
...others
};
}
Any answers on how to type def the {[oldProp]: old, ...others}
line?
Upvotes: 2
Views: 307
Reputation: 1991
Interesting question, but looks like there is no definitive answer. But here is one attempt:
export function renameProperty<
T extends {},
OP extends keyof T,
NP extends string,
R = Omit<T, OP> & Record<NP, T[OP]>
>(oldProp: OP, newProp: NP, { [oldProp]: value, ...others }: T): R {
return {
[newProp]: value,
...others
} as any; // *
}
This has advantage, that returns proper type with oldProp
erased and newProp
added.
i.e
const c = renameProperty("foo", "bar", { foo: 1, baz: "spam", holy: "grenade" });
console.log(c.foo, c.bar, c.baz, c.holy);
/// complains here, that 'foo' is not available in c
/// typeof c.bar === "number"
*
Unfortunately, TS is not able to infer proper type from {[newProp]: value}
and resulting type is { [x: string]: ... }
so unfortunately dreadful as any
is needed (at least i didn't find a way to remove it - not sure if this is a bug or limitation).
Omit
: Exclude property from type
Upvotes: 1