Type Compatibility And Type Casting
Type compatibility
In TypeScript, two types are considered compatible if they have the same structure. This means that, for two types to be compatible, they must have the same properties with the same names and types.
For example, if you have the following two types:
interface Person {
name: string;
age: number;
}
interface Employee {
name: string;
age: number;
salary: number;
}
These two types are considered compatible because they both have the same
name
and age
properties with the same types. This means that you can assign a value of type Person
to a variable of type Employee
and vice versa.On the other hand, if you have the following two types:
interface Person {
name: string;
age: number;
}
interface Employee {
name: string;
salary: number;
}
These two types are not considered compatible because they do not have the same structure. In this case, the
Employee
type is missing the age
property that is present in the Person
type. This means that you cannot assign a value of type Person
to a variable of Employee
, but you can still assign a value of type Employee
to a variable of type Person
because the Employee
type has all the properties of the Person
type.In summary, TypeScript’s type compatibility is based on the structure of the types, and two types are considered compatible if they have the same properties with the same names and types.
Type Casting
Type casting is a way to convert a value from one type to another. This is useful when you know that a value has a certain type, but TypeScript is unable to infer it.
For example, if you have the following code:
let someValue: any = "Hello, world!";
let strLength: number = (someValue as string).length;
In this code,
someValue
is declared as type any
, which means that it can hold a value of any type. However, you know that someValue
contains a string value, so you want to use the string method length
to get the length of the string.To do this, you can use type casting to tell TypeScript that
someValue
is actually a string. This is done by using the as
keyword before the someValue
variable. This tells TypeScript to treat someValue
as a string instead of an any
type.The parentheses around
someValue as string
are necessary because the .
operator has a higher precedence than the as
keyword. Without the parentheses, the code would be interpreted as (someValue as string.length)
, which is not valid. The parentheses ensure that the as
keyword is applied to the someValue
variable before the .
operator is applied to the result.Overall, type casting in TypeScript allows you to convert a value from one type to another when TypeScript is unable to infer the correct type. This is done using the
as
keyword and parentheses to ensure that the type casting is applied to the correct value.