Home > other >  Inconsistent TS2345 when passing function paramter in different ways
Inconsistent TS2345 when passing function paramter in different ways

Time:09-23

I defined an interface named AAA and it has only one member and using the AAA as the function parameter's declaration. When I pass a defined constant variable with two members, the typescript can't detect. However when I pass a literal variable typescript can detect the extra paramter. I don't understand the difference, did someone encounter similar situation?

interface AAA {
  hyYears: Array<any>;
}

function func(process: AAA) {
  console.log(process);
}

const unresolveParams = {
  hyYears: [],
  periodDataId: 1,
};


func(unresolveParams); // why this line can't detect the extra parameter

func({
  hyYears: [],
  periodDataId: 1, // detect the extra parameter. Argument of type '{ hyYears: undefined[]; periodDataId: number; func(unresolveParams: any): any; }' is not assignable to parameter of type 'AAA'. ts(2345)
});

CodePudding user response:

TypeScript generally performs structural type checking. It doesn't care if an object has extra properties bolted on.

Object literals get special treatment and are subject to excess property checking since creating an object and then immediately assigning it somewhere which isn't expecting the periodDataId property is more likely to be an error.

  • Related