Search code examples
javascripttypescriptcastingtypeerror

Type annotations in typescript


interface Test {
   name: string;
   age: number;
}

const subjectObj = {
   name: "Harhsit Singh",
   age: 17,
   height: "6'1",
};

const testObj: Test = subjectObj; //? NO ERROR

const testObj2: Test = {
   name: "Harhsit Singh",
   age: 17,
   height: "6'1", //! ERROR
};

I have created a interface test as shown in the picture, and a test subject named subjectObj and it contains more properties than the type test contains.

Now I have assigned my subjectObj to constant testObj of type test, then declared another constant testObj2 with the same type test and assigned it the same object, but this time initialized it with a new object of same structure as subjectObj.

But now it gives me an error that 'height' does not exist in type 'test', but didn't gave any error when i passed subjectObj as a reference to testObj though it also contains the property height.

I don't know why is this happening, so need some detailed explaination.


Solution

  • Excess property checking happens only when you pass object literals—when you pass in types, you run into the fact that TS never checks for exact types, and assumes that an object with excess types is what you mean.

    That's really owing to the JS culture TS is embedded in. It would be really hard to code in TS against JS interfaces otherwise.