Question:
Making an argument required if generic interface as no properties

Problem

How can I make a function argument required based on whether or not P has any properties besides onClose.

So:

  • If type P has properties besides onClose, props needs to be required and equal to Omit<P, 'onClose'>

  • If type P has no properties besides onClose, props should not be allowed


export interface Closeable {

  onClose: () => void

}


export type WindowOpenFunction = <P extends Closeable>(

  window: ComponentType<P>,

  props: Omit<P, 'onClose'>

) => void


Solution

There's a way to do it by using spread arguments. First we got to find a way to detect if P has no properties besides onClose.


keyof Omit<P, 'onClose'> extends never


means that there's no extra key inside P besides onClose.


Then we can use a type condition to to do the job:


export type WindowOpenFunction = <P extends Closeable>(

  window: P,

  ...args: keyof Omit<P, 'onClose'> extends never ? 

    [] | [undefined] | [Omit<P, 'onClose'>]: [Omit<P, 'onClose'>]

) => void


If props have no extra props then the list of extra arguments can either be an empty tuple of one argument or a tuple of one argument, otherwise, it needs to be a tuple of one argument.


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers