Typescript destructuring with required parameter

僤鯓⒐⒋嵵緔 提交于 2019-12-10 13:34:33

问题


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?


回答1:


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




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/57634041/typescript-destructuring-with-required-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!