Home > OS >  Destructed object declaration in TypeScript
Destructed object declaration in TypeScript

Time:01-27

I can declare destructed function arguments like this:

const List = ({ items, css }: { items: string[], css: string[] }) => {
    
}

but I don't like that I have redundant code. Is there a way to declare it like

const List = ({ items of string[], css of string[] }) => {
    
}

As I usually would need this in React, I think I cannot pass the arguments without the "object wrapper". Does anyone have a solution, especially for passing arguments in React components?

CodePudding user response:

Not possible unfortunately. There is a long running GitHub thread here about this very issue, unfortunately there haven't been any concrete plans to introduce any new syntax to help with this.

CodePudding user response:

Unfortunately not — if you're going to use TypeScript, you'll just have to get used to the fact that it is more verbose than JavaScript.

If you just want to relocate the "type syntax complexity" away from the component implementation, then you can use a type alias, like this:

TS Playground

type ListProps = {
  items: string[];
  css: string[];
};

// Or (subjectively) more concisely:
// type ListProps = Record<"css" | "items", string[]>;

const List = ({ items, css }: ListProps) => {
  // Component implementation
};

  • Related