Home > front end >  Intersection type of generic and 'any' does not narrow down properties
Intersection type of generic and 'any' does not narrow down properties

Time:11-17

Why is it when doing an intersection of two types, one of which is any, I am unable to get TypeScript to guard against additional properties. It looks like the 'any' take precedence over the type that I have defined.

I have the code in a TS Playground I would have expected the code on line 14 to throw an error since b is not a property defined on <P>

function f1<P>(params: { data?: P }) {
  console.log(params.data);
}

function f2<P>(params: { data?: P } & { data?: any }) {
  console.log(params.data);
}

f1<{ a: string }>({ data: { a: "foo" } });
f1<{ a: string }>({ data: { a: 5 } });
f1<{ a: string }>({ data: { a: "foo", b: "foo" } });

f2<{ a: string }>({ data: { a: 5 } });
f2<{ a: string }>({ data: { a: "foo", b: 5 } });

CodePudding user response:

{ data?: P } & { data?: any } becomes { data?: P & any } and therefor data becomes any

just dont use any, use unknown for unknown typings and then type narrowings to use the props

  • Related