16

ES6 is great, it reduced number of codes but typescript for everything just doesn't work.

If I would want to implement type checking for my arguments, which is already been destructed more than one level, wouldn't it be a mess? I think it's enough to use interface to do once checking at the beginning, what do you think? Or you can typecheck everything but don't overuse es6 for better readability.

<div>
      {response.results.map(({id, name, stock: {day: dayStock, month: monthStock}}) => {
        return(
          <div>
            <p>Item: {name}</p>
            <p>Day Stock: {dayStock}</p>
            <p>Month Stock: {monthStock}</p>
            <br />
          </div>
        )
      })}
    </div>

typescript playground: https://codesandbox.io/s/v06ml2y130

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 1
    What you mean by _want to implement type checking for my arguments_ ? It is already type checked - `dayStock` is of type `number` – Aleksey L. Jun 18 '18 at 08:09

1 Answers1

21

If you type your results then you can annotate the destructured object.

type Item = {
    id: number;
    name: string;
    stock: {
        month: number;
        week: number;
        day: number;
    };
}

const response = {
    results: [{
        id: 1,
        name: 'TV',
        stock: {
            month: 10,
            week: 5,
            day: 4
        }
    }]
};

response.results.map(
    ({ id, name, stock: { day: dayStock } }: Item) => dayStock
);
robC
  • 2,592
  • 1
  • 23
  • 28
  • what is the different if I used interface? great answer for this one. –  Jun 18 '18 at 13:10
  • An interface can be extended, or have multiple merged declarations: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10 – robC Jun 18 '18 at 14:14
  • `const {state : {data}} : {state : any} = useLocation();` how could I re-write it without using `any` if `data` is an `number` – Azhar Uddin Sheikh Sep 19 '22 at 14:25