vuvu
vuvu

Reputation: 5318

Why is there no type errors shown if the value comes as variable?

I'm wondering why the compiler this an type error if a value is written directly into if typed variable (result_2) but not if the value is written as variable (result_1). It correct use of typescript anyway?

ts playground

type HasID = {  id: number }

const data = {id: 5, age: 3}

const result_1: HasID = data


// Type '{ id: number; age: number; }' is not assignable to type 'HasID'.
// Object literal may only specify known properties, and 'age' does not exist in type 'HasID'.

const result_2: HasID = {id: 5, age: 3} // Error

Upvotes: 0

Views: 24

Answers (1)

Engam
Engam

Reputation: 1061

I found a blog article about this excate topic. In summary when you assign the object directly to the typed variabel (result_2), the typescript compiler triggers excess property checking.

In result_1 it only checks if data contains all the mandatory properties the type HasId requires.

Take a look at this blog article I found for more information about this topic: https://levelup.gitconnected.com/typescript-excess-property-checks-6ffe5584f450

And this article (Type compatibility) in the typescript documentation: https://www.typescriptlang.org/docs/handbook/type-compatibility.html

Upvotes: 2

Related Questions