Home > Back-end >  Remove nullable property from a custom object type
Remove nullable property from a custom object type

Time:09-27

I'm trying to create a type that has null void and undefined removed.

type TEST = {
  propOne:string
  propTwo: number
  propThree:null  // completely remove this property
}

type CLEAN<T> = { [P in keyof T]: NonNullable<T[P]> };

type FIXED = CLEAN<TEST>

const fixed:FIXED={ // error - it wants propThree property
    propOne:'',
    propTwo:1,
}

TS Playground

CodePudding user response:

You can use key remapping with conditional types to map nullable keys to never which will remove the property from the result type:

type CLEAN<T> = { [P in keyof T as null extends T[P] ? never : P]: T[P] };

Playground

CodePudding user response:

@Psidom Thank you, your answer got me on the right path. However, I've said a need null void and undefined removed. So following the documentation link about key remapping that you posted I've come up with this solution.

type TEST = {
  propOne:string
  propTwo: number
  propThree:void  // completely remove this property
}

type CLEAN<T,K> = { [P in keyof T as T[P] extends K ? never : P]: T[P] };

const fixed:CLEAN<TEST,void | null | undefined>={
    propOne:'',
    propTwo:1,
}

This way I can omit any number of types.

Playground

  • Related