0

I have an interface:

interface User { 
    name: string,
    age: number
}

function:

function test(user: User): void { 

}

and empty object created with the interface:

const user1 = <User>{};
test(user1);

So I don't understand why my code is compiling, because my empty object hasn't the interface keys. How can I prevent compiling if my object is empty and hasn't the interface keys?

1 Answer 1

5

<User>{} is type assertion, which basically means you're telling TypeScript that "Yeah, it is a User alright, don't tell me otherwise". Therefore TypeScript doesn't report any error.

If you want TypeScript to catch your coding error, in this case you should use

const user1: User = {};

instead, and you'll get the error you're asking for. For more information, see this page.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but if I will write const user1 = <User>{z: 4}; I will get an error, so why if I use an empty object it doesn't show me error?
This is because in this case the neither types User and {z: number} overlap the other one. Overlapping is necessary for using type assertion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.