0

while learning in react 16.8 with typescript code base, I came through many diffrent type definition pattern is been followed.

so for the sake of consistency,

which is the right way (recommended or valid) to set a type definition of a es6 arrow method especially when object destructuring comes into picture

so my first question is what is the right way to define (or set, what it called) type of a function

  1. write just after the function name , before =
    const method: MethodType = (state:AlphaState , action: AlphaAction) => {
    return data;
}
  1. after the parameter listing , just before =>
    const method  = (state:AlphaState , action: AlphaAction): MethodType => ({

    })


now second part of my question is if we use object destructuring in parameter then it become more complex .

Where to write parameters type and whether it can be conflicts with parameter typing and function typing signature?

So here is in case of object

  1. write against each property of parameter object, just before each ,
     const appMethod: MethodType = ({state:AppState , action: AppAction}) => ({
     }
  1. after the parameter list, a separate type list with same type order after destructuring done, i.e. after first closing }
    const appMethod: MethodType = ({state , action}:{AppState, AppAction}) => {}

Also welcome any other or recommended style to handle this.

xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • sorry for the typo, actually positing from mobile. – xkeshav Oct 21 '19 at 08:51
  • I am looking for the solution not the smell of why I am asking here ? I am the team lead for my own personal project. – xkeshav Oct 21 '19 at 08:53
  • @zerkms how 1 and 2 are are different, kindly explain. – xkeshav Oct 21 '19 at 08:57
  • 1 and 2 are entirely (functionally) different. 1 states that the *function* itself has the type `MethodType`, i.e. so it only makes sense when `MethodType` is some callable type. 2 states that the closure *returns* `MethodType`, and `MethodType` does not need to be callable. – SOFe Oct 21 '19 at 15:32

1 Answers1

1

To stay short:

  1. MethodType is a type of the method variable. Effectively, a function type.

  2. MethodType is a type of the return value of the arrow function. So it's not comparable to 1, it's different.

  3. It's object destructuring, has nothing to do with typescript: you destructure fields to AppState and AppAction local variables.

  4. It's invalid syntax

3&4 would be written as

const appMethod: MethodType = ({ state, action }: { state: AppState, action: AppAction }) => ({});
zerkms
  • 249,484
  • 69
  • 436
  • 539