OnlyWick
OnlyWick

Reputation: 464

How should I explain this code type checking in Typescript

I'm confused, whether I can use Everyday Types to explain this problem?

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

function fn(user: IUser): void {}

const user = { name: 'bob', age: 18, height: 188 };
fn({ name: 'bob', age: 18, height: 188 }); // error!
fn(user); // no error

Upvotes: 0

Views: 42

Answers (1)

distante
distante

Reputation: 7005

The error comes from Typescript telling you that you are creating a new object there with data that is not needed.

When you use an already created object that fulfils your interface but has another values, it could be a child class or another interface that extends your interface, so having extra items there is the wanted behaviour.

On the other hand, creating a new object on the fly with extra parameters is a sign that you think fn needs a different kind of object to work properly.

Upvotes: 2

Related Questions