1

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

1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.