Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Omit" utility from Typescript have extends any for "K"?

Tags:

typescript

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

Since the parameter "K" of Omit extends keyof any, we have no error given by Typescript when insert a property name which does not exist in the parameter "T".

Omit helps to remove one property which is contained by a Type or Interface. I don't find it logical to freely insert a property that doesn't exist in the givin Type/Interface.

Isn't it better this way:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

What's the actual reason for Typescript to extends keyof any ? And how can I change it for my project ?

like image 545
Sabgramar Avatar asked Nov 03 '25 22:11

Sabgramar


1 Answers

Using K extends keyof any allows for more flexible calls of Omit without having to modify the second type to include only properties that exist in the object. For example, using your version, you wouldn't be able to do:

type BadProps = 'bad1' | 'bad2' | 'bad3';
type Omit2<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type Result = Omit2<{ bad2: 'val2'}, BadProps>

You would have to first construct another type from BadProps. Not that that would be hard, but it'd add unnecessary boilerplate.

like image 128
CertainPerformance Avatar answered Nov 06 '25 14:11

CertainPerformance



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!