Typescript destructuring with required parameter Typescript destructuring with required parameter typescript typescript

Typescript destructuring with required parameter


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


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) {...}


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  }}