What is Structural Typing?
What is Structural Typing?
Structural typing is a type system used in programming languages where type compatibility and equivalence are determined based on the structure of the types rather than their names or other attributes. This approach contrasts with nominal typing, where type compatibility is based on explicit declarations or the names of the types.
In structural typing, two types are considered compatible if they have the same set of properties and methods, regardless of how they were defined or named. This means that an object can be used in any context that expects another object with the same structure, even if the two objects come from different classes or interfaces.
Shape-based Compatibility: The compatibility of types is based on their shape, i.e., the names and types of their properties and methods. If two types have the same shape, they are considered compatible, regardless of their names or where they are defined[1][2][3][5][6][8][11][12][13][14][15][16][17][18][19].
Flexibility and Code Reusability: Structural typing allows for greater flexibility and code reusability. Developers can write functions and components that can operate on a variety of data types, as long as they fit the required structure. This is particularly useful in scenarios where types might come from different libraries or modules[1][2][3][5][6][8][11][12][13][14][15][16][17][18][19].
Duck Typing: Structural typing is closely related to duck typing, a concept where an object's suitability for use is determined by the presence of certain methods and properties, rather than the actual type of the object. The phrase "if it looks like a duck and quacks like a duck, then it probably is a duck" captures the essence of duck typing[1][2][3][5][6][8][11][12][13][14][15][16][17][18][19].
TypeScript is a popular language that uses structural typing. Here's a simple example to illustrate this concept:
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào