U
U
user_of_toster2021-02-21 15:01:37
typescript
user_of_toster, 2021-02-21 15:01:37

What is the logic behind not checking types by variable?

I read the typescript docs:
https://www.typescriptlang.org/docs/handbook/inter...

If I pass an object with the wrong types directly, I get an error:

let mySquare = createSquare({colour: "red", width: 100}); // Argument of type '{ colour: string; width: number; }' is not assignable...

And if you pass the same object through a variable, then there is no error:
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);


The question is - what's the catch and why was it done so? Why are types not checked through variables?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-02-21
@user_of_toster

TypeScript has structural typing , which means that types that are structurally identical are the same type. For example, types { colour: string; width: number; }and { colour: string; } & { width: number; }are the same type.
In addition, TypeScript has a type hierarchy, that is, there are relationships between types when one type is a subtype of another. For example, type { colour: string; width: number; }is a subtype of { width: number; }. The value of a subtype can be seamlessly assigned to a variable of the parent type. The type value { colour: string; width: number; }contains all the fields required by the type { width: number; }, which means that assigning the first to the second is guaranteed not to lead to an error, but the resulting code will only have access to part of the data. This behavior suits the example

let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);

However, when we assign a literal, the type hierarchy is less taken into account, since the subtype will restrict us from getting data later, and there are no other ways to get this data. This is why TypeScript complains about passing a literal here . The color field will simply be lost, since the type will not give access to it. createSquare({colour: "red", width: 100});{ width: number; }

A
Alexey Yarkov, 2021-02-21
@yarkov

Now make the color property required ))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question