Home > Back-end >  Why Omit from type of intersection with Record<string, any> makes all values any?
Why Omit from type of intersection with Record<string, any> makes all values any?

Time:07-13

Why in this example type of c.b infers as any

interface A {
    a: string;
    b: string;
}

type B = A & Record<string, any>

declare let b: B;

b.b; // string type

type C = Omit<B, 'a'>;

declare let c: C;

c.b; // Why after Omit type of `c.b` infers as `any`

CodePudding user response:

This happens the way Omit works.

Lets look at how it's defined:

type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }

You see that it uses Exclude<keyof T, K> to defines the keys.

In our case here we have

type Keys = Exclude<keyof B, 'a'> // string. 

and the keys are more precisely defined by :

keyof ({ 'a': string } & Record<string, any>) 

which results to string.

Therefore it will match the values from Record<string, any> : any

Playground

  • Related