How Can i change write my method in TypeScript

typescript function as parameter
typescript arrow function return type
typescript interface function
typescript generic function
typescript callback type
typescript anonymous function
typescript function overloading
typescript type
 public renameJson(json: any): any {
    return Object.keys(json).reduce(
      (s, item) =>
        this.isUpperCase(item.charAt(1))
          ? {
              ...s,
              [item.toLowerCase()]: this.getTransform(json[item])
            }
          : {
              ...s,
              [this.getFirstLetterToLowerCase(item)]: this.getTransform(
                json[item]
              )
            },
      {}
    );
  }

I wrote this method in typescript, but I am bothered by duplicate content. I would like to write it better, more or less like this:

public renameJson2(json: any): any {
    return Object.keys(json).reduce(
        (s, item) =>
        {
            ...s,
            [
                this.isUpperCase(item.charAt(1))
                ? item.toLowerCase()
                : this.getFirstLetterToLowerCase(item)
            ]
            : this.getTransform(json[item])
        },
        {}
    );
}

but my compiler says it's a mistake and i don't know why.

There are a few different things going on here.

TL;DR:

interface IPojo {
  [key: string]: any
}

class Foo {
  public getTransform(...xs: any[]) {
    return xs;
  }

  public renameJson2(json: IPojo): IPojo {
    return Object.keys(json).reduce(
      (obj: IPojo, item: string, ...xtra: any[]) => {
        const [first, ...rest] = item.split('');
        // I don't have your other methods, so replace this
        // regex check if you wish.
        const key = first.match(/[A-Z]/)
          ? item.toLowerCase()
          : first.toLowerCase() + rest.join('');

        obj[key] = this.getTransform(json[item]);
        return obj;
      }, {}
    );
  }
}

You'll have to fill in getTransform yourself, but here's the playground

Problems with the original:

  1. A returned object from an arrow function with no body should be wrapped in parens to avoid the parser confusing it with the body of the function.
  2. The callback to Array.prototype.reduce gets four arguments (accumulator, item, theArray, thisValue), not two.
  3. Using any in your signatures would have involved lots of casting, so I added a generic object interface.
  4. Concision is nice, but readability is nicer. Don't be afraid of temp variables where they make sense, also on an array method the Jitter will probably optimize them out of existence after the first pass or two.

Function Types, This allows you to choose the most appropriate approach for your application, Now that we've typed the function, let's write the full type of the function out by we would need to change the order of parameters in the function, putting the first​  Extension-method gives you the power to add new methods to existing types. You don’t have to create a new derived-type. You can write extension-method of any data-type you want. It’s just like writing a simple function of a specific class. These are static methods. We can extend any class or interface to write our own extension-method but remember, we cannot override the existing ones

That's because the curly brackets that you intend for the object being constructed are being treated as the curly brackets of the reducer function. You can just add a return statement in your reducer function for the object like this -

 return Object.keys(json).reduce(
    (s, item) =>
    {
       return { ...s,
        [
            this.isUpperCase(item.charAt(1))
            ? item.toLowerCase()
            : this.getFirstLetterToLowerCase(item)
        ]
        : this.getTransform(json[item]) 
        }
    },
   {}
 );

Class Decorators, NOTE Decorators are an experimental feature that may change in future releases​. For example, given the decorator @sealed we might write the sealed function as NOTE The Property Descriptor will be undefined if your script target is less  That's TypeScript saying that this method doesn't return any value, and when I add a return value, that type changes. If I hover over the method again, I can see that TypeScript has now determined that the method returns a string value. Likewise, let's see what happens when I change the value that I'm returning to the length of the variable.

First, to fix the issue you're seeing. The issue is when you use curly braces after an arrow function, JS expects a function body to appear. So this is effectively what you're writing

return Object.keys(json).reduce(function (s: any, item: any) {
  ...s,
  [
    this.isUpperCase(item.charAt(1))
      ? item.toLowerCase()
      : this.getFirstLetterToLowerCase(item)
  ]
  : this.getTransform(json[item])
});

I converted the arrow function to a normal function so you could see what TS is seeing.

To fix that issue, you can do one of two things. Either wrap the object in parenthesis or wrap the object in a function body and return it.

Now, a suggestion for doing this a little more efficiently. Simply use forEach and an object that can accumulate the properties instead of reduce and recreating the object each time (playground snippet)

public renameJson2(json: any): any {
    const result: any = {};

    Object.keys(json).forEach((key: string) => {
        const resultKey = this.isUpperCase(key.charAt(1)) ? key.toLowerCase() : this.getFirstLetterToLowerCase(key);

        result[resultKey] = this.getTransform(json[key]);
    });

    return result;
}

Use TypeScript to Write Better JavaScript, This means that introducing TypeScript to your current JavaScript code is easy—​just But by simply renaming the file to .ts and continuing to write JavaScript like you've For instance, consider the very simple add function, as shown below, into my sausage factory or even worse, changing my internal implementation,  You cannot change a variable's type in TypeScript, that's just the opposite TS was made for. Instead, you can declare a variable as "any", which would be equivalent to a classic "var" variable in JS, untyped. Once a variable is declared, you will not be able to retype it.

That's because arrow functions are waiting for curly braced characters {} after the arrow =>, but you want to return the curly braced object itself. I would suggest wrapping your object with parenthesis, like the following:

public renameJson2(json: any): any {
    return Object.keys(json).reduce(
      (s, item) => ({
        ...s,
        [this.isUpperCase(item.charAt(1))
          ? item.toLowerCase()
          : this.getFirstLetterToLowerCase(item)]: this.getTransform(json[item])
      }),

      {}
    );
  }

Typescript is changing how I write code, Typescript is changing how I write code. function processMessage(message) { switch(message. type Message = { type: 'text' | 'picture' | 'video' | 'sticker', sender: string; } function processMessage(message: Message): number { switch(message. Recursion and TypeScript Functions Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.

Write Beautiful OO Classes with TypeScript, I've been writing Typescript for ~7 months now, and it has been fantastic. TypeScript allows us also to define properties and methods that belong to then we don't want other coders working on this class to change this field. and you want to deepen your TS understanding, go and read the TypeScript  TypeScript, developed by Microsoft, is a superset of JavaScript. It features static typing, class, and interface. Comparing to JavaScript, One of my favorite TypeScript features is that we can create a TypeScript declaration file (.d.ts) for IntelliSense in Visual Studio Code or other supported IDEs. In this article, I will share how to write a

TypeScript Interfaces, Interface is a structure that defines the contract in your application. It defines the TypeScript interface is also used to define a type of a function. This ensures  TypeScript can figure the return type out by looking at the return statements, so we can also optionally leave this off in many cases. Writing the function type # Now that we’ve typed the function, let’s write the full type of the function out by looking at each piece of the function type.

TypeScript Programming with Visual Studio Code, If you have npm installed, you can install TypeScript globally ( -g ) on your computer by: Semantic highlighting can change colors based on: As you write a TypeScript function call, VS Code shows information about the function signature  Static Method in TypeScript Whenever you want to access methods of a class (but the method of the class is not static), then it is necessary to create an object of that class. But if the static keyword is used with a member function (method), that method is automatically invoked without creating an object of the class, you just invoke that

Comments
  • Have you considered doing a forEach over the keys and building the object one key at a time instead of rebuilding a new object each iteration?
  • very thank you, I am grateful to you
  • Point 2 doesn't matter. TS doesn't care if you ignore extra parameters (and neither does JS).