Omit never types in typescript

Issue

Is it possible somehow to omit all never types from a type in typescript? I have a type that takes two other types, and based on values, generates a third type, and sets all incorrectly or differently valued elements to never:

type MapForeignKeys<TExpandMap extends expandMap, TForeignKeys> = {
    [Prop in keyof TExpandMap]: 
        TExpandMap[Prop] extends { association: 'belongsTo', instance: BaseModel, foreignKey: any } 
        ? TExpandMap[Prop]['instance']['_creationAttributes'] | TExpandMap[Prop]['instance'] | TForeignKeys[TExpandMap[Prop]['foreignKey']] 
        : never 
                       
}

When I try to use this type, the output contains properties that should be set to never, instead of omitting those types from the type definition, thus this becomes unusable.

A simple example that describes my problem can be found in this playground link

EDIT: A new link with some reproductible example of the problem

Solution

One of the possible ways to omit keys is using as clause in mapped types.

You can filter out keys by producing never via a conditional type

type OmitNever<T> = { [K in keyof T as T[K] extends never ? never : K]: T[K] }

So here we’re replacing keys having never value with never keys and eventually they are omitted.

Playground

Answered By – Aleksey L.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published