Home > Mobile >  How do you write the types for a function in-place destructuring in Typescript?
How do you write the types for a function in-place destructuring in Typescript?

Time:01-10

A user will pass an hisObject to myFn. See this simple example:

type HisType = { a:string, b:number };

function myFn( { a, b } = hisObject): void {  
  console.log(a,b)
};

But could can we include that hisObject is of type HisType to avoid errors?

CodePudding user response:

Without default argument:

function myFn({ a, b }: HisType): void {
  console.log(a, b);
}

With default argument (hisObject points to the default value):

// This exists earlier in the program
const hisObject: HisType = /* ... */;

function myFn({ a, b }: HisType = hisObject): void {
  console.log(a, b);
}
  •  Tags:  
  • Related