Search code examples
javascripttypescriptobjectecmascript-6destructuring

Typescript destructuring with required parameter


Edit Sorry my question was a bit unclear. I want to enforce that the getList Parameter is always required. So I don't have a default value for it. e.g I want the user always to supply a getlist

I'm trying to create a constuctor with some optional parameters and some required

export class PageConfig {
    constructor({
        isSliding = false,
    }: {
        isSliding?: boolean
        getList: (pagingInfo: PagingInfo) => Observable<any>
    } = {  }) { }
}

When I do this I'm getting an error

getList is missing in type '{}' but required in type ...

I would like to be able to use this in a class like so:

class UsersPage {

    config = new pageConfig({ this.getList })    

    getList(pagingInfo: PagingInfo) {
      // do work...
    }
}

Note: I've simplified the class for this example but I have a lot more properties, I'd like to leverage desturcturing so I don't have to configure the instantiation of my classes other than from the declaration

How can I enforce that getList must be passed during destructuring?


Solution

  • You use a default value {} for the PageConfig constructor argument, but you marked getList as required in the type. If I understand you correctly, you want to have the constructor argument and getList always set, so change your code to:

    export class PageConfig {
      constructor({
        getList,
        isSliding = false
      }: {
        getList: (pagingInfo: PagingInfo) => Observable<any>;
        isSliding?: boolean;
      }) {
        … // use getList and isSliding
      }
    }
    

    This syntax (destructuring with default values) can be a bit cumbersome sometimes. It gets clearer, when you extract the constructor argument type.

    TypeScript docs example