Types in destructured value of object in function-like parameter's function

956 views Asked by At

So, we have some function:

const someVal = func(customObject => {console.log(customObject.data.users)});

We can rewrite this function with object-destruction syntax to make it more pretty and laconic for users value:

const someVal = func(({ data: { users } = {}) => {console.log(users)});

Now imagine, that users value must be described by some typescript interface.

How it should be done inline?

Like this?

 const someVal = func(({ data: { users } = {} : { data: { users : UserInterface }) => {console.log(users)});

UPD. data is generic value variable

1

There are 1 answers

2
John Sloat On

You could do it inline but it can get quite messy. I generally prefer to define types for better readability:

type SomeValInput = {
  data: {
    users?: UserInterface;
  };
};
type SomeVal = (data: SomeValInput) => void;
const someVal: SomeVal = ({ data: { users } }) => console.log(users || {});

I didn't include the default value in the destructuring, as I've had trouble with using that in combination with typescript in the past.