2

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?

Kim Gentes
  • 1,496
  • 1
  • 18
  • 38

1 Answers1

1

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

Zbigniew Zagórski
  • 1,921
  • 1
  • 13
  • 23
  • @Zbigiew Zagorski : I am on Typscript version 3.4.5, and according to the link you provided re: Omit, I added the following line to the top of the file containing the function. Does that sound correct? -- `type Omit = Pick>;` – Kim Gentes May 23 '19 at 00:30
  • 1
    @KimGentes: Yes, that's exactly what i meant. For some reason, `Omit` is not included in typescript library, so everyone have to repeat this when needed. – Zbigniew Zagórski May 23 '19 at 07:53
  • 1
    TS 3.5 will finally have Omit in standard library: https://devblogs.microsoft.com/typescript/announcing-typescript-3-5/#the-omit-helper-type – Zbigniew Zagórski May 30 '19 at 12:16
  • Thanks for letting me know! – Kim Gentes May 31 '19 at 17:20