Answer the question
In order to leave comments, you need to log in
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...
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);
Answer the question
In order to leave comments, you need to log in
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);
createSquare({colour: "red", width: 100});
{ width: number; }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question