Search code examples
typescriptdestructuring

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


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

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

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

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

How do you write the types for a function in-place destructuring in TypeScript?


Solution

  • Without a default argument:

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

    With a 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);
    }