Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omit never types in typescript

Tags:

typescript

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

like image 827
Adam Baranyai Avatar asked Feb 06 '26 22:02

Adam Baranyai


1 Answers

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

like image 136
Aleksey L. Avatar answered Feb 09 '26 09:02

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!