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?

3 answers

  • answered 2019-08-23 23:42 Jack Bashford

    You want to remove the default, and also change the parameter order - required parameters always come before optional parameters:

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

  • answered 2019-08-23 23:53 chrismclarke

    One option if it is the case that all constructor parameters are optional/have a default value would be simply to use a Partial config in the constructor and merge with defaults, e.g.

    interface IPageConfigConstructor {
      isSliding: boolean;
      getList: (pagingInfo) => Observable<any>;
    }
    const DEFAULT_CONFIG:IPageConfigConstructor = {
      isSliding: true,
      getList: (pagingInfo) => null
    }
    
    class PageConfig {
      constructor(config: Partial<IPageConfigConstructor>) {
        const mergedConfig:IPageConfigConstructor = {...DEFAULT_CONFIG,...config}
      }
    }
    
    class UsersPage {
      config = new PageConfig({getList:(pagingInfo)=>this.getList(pagingInfo)});
    
      getList(pagingInfo) {
        // do work...
        return new Observable
      }
    }
    

  • answered 2019-08-24 10:22 ford04

    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({
        isSliding = false
      }: {
        isSliding?: boolean;
        getList: (pagingInfo: PagingInfo) => Observable<any>;
      }) {}
    }
    

    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