Home > Mobile >  How to exclude a void type on a union type?
How to exclude a void type on a union type?

Time:11-18

Hello guys I have a custom generic type P that is defined like this P extends Record<string, unknown> | void

And I want to have an exists function

export class Parameters<P extends Record<string, unknown> | void> {
        private params: P
        constructor(params: P) {
                this.params = params 
        }
        public exists(field: keyof P): boolean {
                return field in this.params
        }
}

compilation error

CodePudding user response:

First make sure params in not undefined

export class Parameters<P extends Record<string, unknown> | void> {
    params!: P
    public exists(field: P): boolean {
        return this.params && field in this.params
    }
}

Playground

  • Related